Поделиться через


How to: Group Items in a Windows Forms ListView Control

With the grouping feature of the ListView control, you can display related sets of items in groups. These groups are separated on the screen by horizontal group headers that contain the group titles. You can use ListView groups to make navigating large lists easier by grouping items alphabetically, by date, or by any other logical grouping. The following image shows some grouped items.

ListView grouped items

ListView Groups

To enable grouping, you must first create one or more groups either in the designer or programmatically. After a group has been defined, you can assign ListView items to groups. You can also move items from one group to another programmatically.

Note

ListView groups are available only on Windows XP Home Edition, Windows XP Professional, Windows Server 2003 when your application calls the Application.EnableVisualStyles method. On earlier operating systems, any code relating to groups has no effect and the groups will not appear. For more information, see ListView.Groups.

To add groups

  • Use the Add method of the Groups collection.

    ' Adds a new group that has a left-aligned header
    ListView1.Groups.Add(New ListViewGroup("Group 1", _
     HorizontalAlignment.Left))
    
    // Adds a new group that has a left-aligned header
    listView1.Groups.Add(new ListViewGroup("List item text",
        HorizontalAlignment.Left));
    

To remove groups

  • Use the RemoveAt or Clear method of the Groups collection.

    The RemoveAt method removes a single group; the Clear method removes all groups from the list.

    Note

    Removing a group does not remove the items within that group.

    ' Removes the first group in the collection.
    ListView1.Groups.RemoveAt(0)
    ' Clears all groups:
    ListView1.Groups.Clear()
    
    // Removes the first group in the collection.
    listView1.Groups.RemoveAt(0);
    // Clears all groups.
    listView1.Groups.Clear();
    

To assign items to groups or move items between groups

  • Set the ListViewItem.Group property of individual items.

    ' Adds the first item to the first group
    ListView1.Items.Item(0).Group = ListView1.Groups(0)
    
    // Adds the first item to the first group
    listView1.Items[0].Group = listView1.Groups[0];
    

See Also

Tasks

How to: Add and Remove Items with the Windows Forms ListView Control

Reference

ListView Control Overview (Windows Forms)

ListView

ListView.Groups

ListViewGroup

Concepts

Windows XP Features and Windows Forms Controls

Other Resources

ListView Control (Windows Forms)