Introduction
ListView
control is an important but complex control in the WinForm environment. Group behavior is added into this control, but unfortunately, we can't collapse or expand the group.
I'll show how to use some simple code to add collapse/expand behavior on the ListView
control.
This is a sample image on Windows Vista and Windows Server 2008:
Default group without Collapse/Expand behavior
Group with Collapse/Expand behavior
Using the Code
-
Define ListView
group struct
wrapper:
[StructLayout(LayoutKind.Sequential)]
public struct LVGROUP
{
public int cbSize;
public int mask;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszHeader;
public int cchHeader;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszFooter;
public int cchFooter;
public int iGroupId;
public int stateMask;
public int state;
public int uAlign;
}
-
Define the ENUM
data:
public enum GroupState
{
COLLAPSIBLE = 8,
COLLAPSED = 1,
EXPANDED = 0
}
-
Interop for SendMessage
function:
[DllImport("user32.dll")]
static extern int SendMessage
(IntPtr window, int message, int wParam, IntPtr lParam);
-
Kernel method to set collapse/expand behavior on the ListView
group:
private void SetGroupCollapse(GroupState state)
{
for (int i = 0; i <= aoc.Groups.Count; i++){
LVGROUP group = new LVGROUP();
group.cbSize = Marshal.SizeOf(group);
group.state = (int)state;
group.mask = 4;
group.iGroupId = i;
IntPtr ip = IntPtr.Zero;
try{
ip = Marshal.AllocHGlobal(group.cbSize);
Marshal.StructureToPtr(group, ip, true);
SendMessage(aoc.Handle, 0x1000 + 147, i, ip);
LVM_SETGROUPINFO (LVM_FIRST + 147)
}
catch (Exception ex){
System.Diagnostics.Trace.WriteLine
(ex.Message + Environment.NewLine + ex.StackTrace);
}
finally{
if (null != ip) Marshal.FreeHGlobal(ip);
}
}
}
Points of Interest
#define LVM_SETGROUPINFO (LVM_FIRST + 147)
#define ListView_SetGroupInfo(hwnd, iGroupId, pgrp) \
SNDMSG((hwnd), LVM_SETGROUPINFO, (WPARAM)(iGroupId), (LPARAM)(pgrp))
The above is the definition from SDK file: commctrl.h.
Limitations
- In the current version, the rightmost collapse/expand icon doesn't work. :(
- The collapse/expand behavior only exist in Windows Vista and Win2k8 systems.
History
- 27th November, 2008: Initial post