Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

ListViewGroupCollection Class

Note: This class is new in the .NET Framework version 2.0.

Represents the collection of groups within a ListView control.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)

public class ListViewGroupCollection : IList, ICollection, IEnumerable
public class ListViewGroupCollection implements IList, ICollection, 
	IEnumerable
public class ListViewGroupCollection implements IList, ICollection, 
	IEnumerable

Use the ListView.Groups property to get the ListViewGroupCollection associated with a ListView control. This collection contains the ListViewGroup objects that represent the groups shown in the control when the ListView.View property is set to a value other than View.List. Any items that are not assigned to a group will appear in the default group, which has the header label "DefaultGroup{0}". The default group is not contained in the ListView.Groups collection, and cannot be altered. It is primarily useful in debugging to ensure that all items have been properly added to groups. If there are no groups in the ListView.Groups collection, the grouping feature is disabled.

Use the Add method to add a single group to the collection. Use the Insert method to add a group at a particular index within the collection. To remove a group, use the Remove method. Use the RemoveAt method to remove the group at a particular index.

You cannot add a ListViewGroup to the collection more than once. To reposition a group within the collection, it must first be removed from the collection, and then inserted at the desired location. Use the Contains method to determine whether a particular group is already in the collection. To retrieve the index of a group within the collection, use the IndexOf method. You can get or set the group at a particular index with the Item indexer.

Use the AddRange method to add multiple groups to the collection. You can add multiple groups either as an array of groups or as a ListViewGroupCollection that you retrieve through the ListView.Groups property of another ListView control. Use the Clear method to remove all the groups from the collection.

NoteNote

The Remove, RemoveAt, and Clear methods remove groups from the collection, but do not remove any items from the ListView control. If there are no groups in the ListView.Groups collection, the grouping feature is disabled and all items in the control are displayed normally.

The AddRange and Clear methods are useful when you want to provide multiple ways to group the items in a ListView control. To do this, create multiple group arrays. To change the grouping, first use the Clear method to remove all the groups from the collection, then use the AddRange method to add the next array of groups to display.

Use the CopyTo method to copy the groups in a collection to a compatible array starting at a specified index. This is useful, for example, when you want to sort the groups in the collection using the System.Array.Sort method. To do this, copy the groups into a compatible array, then sort the array. Next, use the Clear method to remove all the groups from the collection, then use the AddRange method to add the sorted array back to the collection.

Use the Count property to determine how many groups are in the collection. To iterate through the collection, use the IEnumerator returned from the GetEnumerator method.

NoteNote

The grouping feature is available only on Windows XP and the Windows Server 2003 family when your application calls the Application.EnableVisualStyles method. On earlier operating systems, any code relating to groups will be ignored and the groups will not appear. As a result, any code that depends on the grouping feature might not work correctly. You might want to include a test that determines whether the grouping feature is available, and provide alternate functionality when it is unavailable. For example, you might want to provide alternate sorting when running on operating systems that do not support sorting by group.

The insertion mark feature is provided by the same library that provides the operating system themes feature. To check for the availability of this library, call the FeatureSupport.IsPresent(Object) method overload and pass in the OSFeature.Themes value.

The following example demonstrates how to use the ListView grouping feature to organize items by subitem value in the details view. This form of grouping is similar to the grouping used in Windows Explorer. In the example, the groups are created dynamically. For each subitem column, one group is created for each unique subitem value. For the parent item column, one group is created for each unique initial letter. Clicking the header of a column sorts the items into the groups created for that column. Clicking the same column header again reverses the order of the groups.

using System;
using System.Collections; 
using System.Windows.Forms;

public class ListViewGroupsExample : Form
{
    private ListView myListView;

    // Determine whether Windows XP or a later
    // operating system is present.
    private bool isRunningXPOrLater = 
        OSFeature.Feature.IsPresent(OSFeature.Themes);

    // Declare a Hashtable array in which to store the groups.
    private Hashtable[] groupTables;

    // Declare a variable to store the current grouping column.
    int groupColumn = 0;

    public ListViewGroupsExample()
    {
        // Initialize myListView.
        myListView = new ListView();
        myListView.Dock = DockStyle.Fill;
        myListView.View = View.Details;
        myListView.Sorting = SortOrder.Ascending;

        // Create and initialize column headers for myListView.
        ColumnHeader columnHeader0 = new ColumnHeader();
        columnHeader0.Text = "Title";
        columnHeader0.Width = -1;
        ColumnHeader columnHeader1 = new ColumnHeader();
        columnHeader1.Text = "Author";
        columnHeader1.Width = -1;
        ColumnHeader columnHeader2 = new ColumnHeader();
        columnHeader2.Text = "Year";
        columnHeader2.Width = -1;

        // Add the column headers to myListView.
        myListView.Columns.AddRange(new ColumnHeader[] 
            {columnHeader0, columnHeader1, columnHeader2});

        // Add a handler for the ColumnClick event.
        myListView.ColumnClick += 
            new ColumnClickEventHandler(myListView_ColumnClick);

        // Create items and add them to myListView.
        ListViewItem item0 = new ListViewItem( new string[] 
            {"Programming Windows", 
            "Petzold, Charles", 
            "1998"} );
        ListViewItem item1 = new ListViewItem( new string[] 
            {"Code: The Hidden Language of Computer Hardware and Software", 
            "Petzold, Charles", 
            "2000"} );
        ListViewItem item2 = new ListViewItem( new string[] 
            {"Programming Windows with C#", 
            "Petzold, Charles", 
            "2001"} );
        ListViewItem item3 = new ListViewItem( new string[] 
            {"Coding Techniques for Microsoft Visual Basic .NET", 
            "Connell, John", 
            "2001"} );
        ListViewItem item4 = new ListViewItem( new string[] 
            {"C# for Java Developers", 
            "Jones, Allen & Freeman, Adam", 
            "2002"} );
        ListViewItem item5 = new ListViewItem( new string[] 
            {"Microsoft .NET XML Web Services Step by Step", 
            "Jones, Allen & Freeman, Adam", 
            "2002"} );
        myListView.Items.AddRange(
            new ListViewItem[] {item0, item1, item2, item3, item4, item5});

        if (isRunningXPOrLater)
        {
            // Create the groupsTable array and populate it with one 
            // hash table for each column.
            groupTables = new Hashtable[myListView.Columns.Count];
            for (int column = 0; column < myListView.Columns.Count; column++)
            {
                // Create a hash table containing all the groups 
                // needed for a single column.
                groupTables[column] = CreateGroupsTable(column);
            }

            // Start with the groups created for the Title column.
            SetGroups(0);
        }

        // Initialize the form.
        this.Controls.Add(myListView);
        this.Size = new System.Drawing.Size(550, 330);
        this.Text = "ListView Groups Example";
    }

    [STAThread]
    static void Main() 
    {
        Application.EnableVisualStyles();
        Application.Run(new ListViewGroupsExample());
    }

    // Groups the items using the groups created for the clicked 
    // column.
    private void myListView_ColumnClick(
        object sender, ColumnClickEventArgs e)
    {
        // Set the sort order to ascending when changing
        // column groups; otherwise, reverse the sort order.
        if ( myListView.Sorting == SortOrder.Descending || 
            ( isRunningXPOrLater && (e.Column != groupColumn) ) )
        {
            myListView.Sorting = SortOrder.Ascending;
        }
        else 
        {
            myListView.Sorting = SortOrder.Descending;
        }
        groupColumn = e.Column;

        // Set the groups to those created for the clicked column.
        if (isRunningXPOrLater)
        {
            SetGroups(e.Column);
        }
    }

    // Sets myListView to the groups created for the specified column.
    private void SetGroups(int column)
    {
        // Remove the current groups.
        myListView.Groups.Clear();

        // Retrieve the hash table corresponding to the column.
        Hashtable groups = (Hashtable)groupTables[column];

        // Copy the groups for the column to an array.
        ListViewGroup[] groupsArray = new ListViewGroup[groups.Count];
        groups.Values.CopyTo(groupsArray, 0);

        // Sort the groups and add them to myListView.
        Array.Sort(groupsArray, new ListViewGroupSorter(myListView.Sorting));
        myListView.Groups.AddRange(groupsArray);

        // Iterate through the items in myListView, assigning each 
        // one to the appropriate group.
        foreach (ListViewItem item in myListView.Items)
        {
            // Retrieve the subitem text corresponding to the column.
            string subItemText = item.SubItems[column].Text;

            // For the Title column, use only the first letter.
            if (column == 0) 
            {
                subItemText = subItemText.Substring(0, 1);
            }

            // Assign the item to the matching group.
            item.Group = (ListViewGroup)groups[subItemText];
        }
    }

    // Creates a Hashtable object with one entry for each unique
    // subitem value (or initial letter for the parent item)
    // in the specified column.
    private Hashtable CreateGroupsTable(int column)
    {
        // Create a Hashtable object.
        Hashtable groups = new Hashtable();

        // Iterate through the items in myListView.
        foreach (ListViewItem item in myListView.Items)
        {
            // Retrieve the text value for the column.
            string subItemText = item.SubItems[column].Text;

            // Use the initial letter instead if it is the first column.
            if (column == 0) 
            {
                subItemText = subItemText.Substring(0, 1);
            }

            // If the groups table does not already contain a group
            // for the subItemText value, add a new group using the 
            // subItemText value for the group header and Hashtable key.
            if (!groups.Contains(subItemText))
            {
                groups.Add( subItemText, new ListViewGroup(subItemText, 
                    HorizontalAlignment.Left) );
            }
        }

        // Return the Hashtable object.
        return groups;
    }

    // Sorts ListViewGroup objects by header value.
    private class ListViewGroupSorter : IComparer
    {
        private SortOrder order;

        // Stores the sort order.
        public ListViewGroupSorter(SortOrder theOrder) 
        { 
            order = theOrder;
        }

        // Compares the groups by header value, using the saved sort
        // order to return the correct value.
        public int Compare(object x, object y)
        {
            int result = String.Compare(
                ((ListViewGroup)x).Header,
                ((ListViewGroup)y).Header
            );
            if (order == SortOrder.Ascending)
            {
                return result;
            }
            else 
            {
                return -result;
            }
        }
    }

}

import System.*;
import System.Collections.*;
import System.Windows.Forms.*;

public class ListViewGroupsExample extends Form
{
    private ListView myListView;
    private boolean isRunningXPOrLater = false;

    // Declare a Hashtable array in which to store the groups.
    private Hashtable groupTables[];

    // Declare a variable to store the current grouping column.
    private int groupColumn = 0;

    public ListViewGroupsExample()
    {
        // Initialize myListView.
        myListView = new ListView();
        myListView.set_Dock(DockStyle.Fill);
        myListView.set_View(View.Details);
        myListView.set_Sorting(SortOrder.Ascending);
        // Create and initialize column headers for myListView.
        ColumnHeader columnHeader0 = new ColumnHeader();
        columnHeader0.set_Text("Title");
        columnHeader0.set_Width(-1);
        ColumnHeader columnHeader1 = new ColumnHeader();
        columnHeader1.set_Text("Author");
        columnHeader1.set_Width(-1);
        ColumnHeader columnHeader2 = new ColumnHeader();
        columnHeader2.set_Text("Year");
        columnHeader2.set_Width(-1);
        // Add the column headers to myListView.
        myListView.get_Columns().AddRange(new ColumnHeader[] { 
            columnHeader0, columnHeader1, columnHeader2 });
        // Add a handler for the ColumnClick event.
        myListView.add_ColumnClick(new ColumnClickEventHandler(
            myListView_ColumnClick));
        // Create items and add them to myListView.
        ListViewItem item0 = new ListViewItem(new String[] { 
            "Programming Windows", "Petzold, Charles", "1998" });
        ListViewItem item1 = new ListViewItem(new String[] { 
            "Code: The Hidden Language of Computer Hardware and Software", 
            "Petzold, Charles", "2000" });
        ListViewItem item2 = new ListViewItem(new String[] { 
            "Programming Windows with C#", "Petzold, Charles", "2001" });
        ListViewItem item3 = new ListViewItem(new String[] { 
            "Coding Techniques for Microsoft Visual Basic .NET", "Connell, John",
            "2001" });
        ListViewItem item4 = new ListViewItem(new String[] { 
            "C# for Java Developers", "Jones, Allen & Freeman, Adam", 
            "2002" });
        ListViewItem item5 = new ListViewItem(new String[] { 
            "Microsoft .NET XML Web Services Step by Step", 
            "Jones, Allen & Freeman, Adam", "2002" });
        myListView.get_Items().AddRange(new ListViewItem[] { 
            item0, item1, item2, item3, item4, item5 });
        // Determine whether Windows XP or a later 
        // operating system is present.
        if (System.Environment.get_OSVersion().get_Version().get_Major() > 5 
            || (System.Environment.get_OSVersion().get_Version().get_Major() 
            == 5 && System.Environment.get_OSVersion().get_Version().get_Minor() 
            >= 1)) {
            isRunningXPOrLater = true;
        }

        if (isRunningXPOrLater) {
            // Create the groupsTable array and populate it with one 
            // hash table for each column.
            groupTables = new Hashtable[myListView.get_Columns().get_Count()];
            for (int column = 0; column < myListView.get_Columns().get_Count(); 
                column++) {
                // Create a hash table containing all the groups 
                // needed for a single column.
                groupTables.set_Item(column, CreateGroupsTable(column));
            }
            // Start with the groups created for the Title column.
            SetGroups(0);
        }
        // Initialize the form.
        this.get_Controls().Add(myListView);
        this.set_Size(new System.Drawing.Size(550, 330));
        this.set_Text("ListView Groups Example");
    } //ListViewGroupsExample

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new ListViewGroupsExample());
    } //main

    // Groups the items using the groups created for the clicked 
    // column.
    private void myListView_ColumnClick(Object sender, 
        ColumnClickEventArgs e)
    {
        // Set the sort order to ascending when changing
        // column groups; otherwise, reverse the sort order.
        if (myListView.get_Sorting().Equals(SortOrder.Descending) 
            || (isRunningXPOrLater && e.get_Column() != groupColumn)) {
            myListView.set_Sorting(SortOrder.Ascending);
        }
        else {
            myListView.set_Sorting(SortOrder.Descending);
        }
        groupColumn = e.get_Column();
        // Set the groups to those created for the clicked column.
        if (isRunningXPOrLater)
        {
            SetGroups(e.get_Column());
        }
    } //myListView_ColumnClick

    // Sets myListView to the groups created for the specified column.
    private void SetGroups(int column)
    {
        // Remove the current groups.
        myListView.get_Groups().Clear();
        // Retrieve the hash table corresponding to the column.
        Hashtable groups = (Hashtable)groupTables.get_Item(column);
        // Iterate through the items in myListView, assigning each 
        // one to the appropriate group.
        for (int iCtr = 0; iCtr < myListView.get_Items().get_Count(); iCtr++) {
            ListViewItem item = myListView.get_Items().get_Item(iCtr);
            // Retrieve the subitem text corresponding to the column.
            String subItemText = item.get_SubItems().get_Item(column).get_Text();
            // For the Title column, use only the first letter.
            if (column == 0) {
                subItemText = subItemText.Substring(0, 1);
            }
            // Assign the item to the matching group.
            item.set_Group((ListViewGroup)(groups.get_Item(subItemText)));
        }
        // Copy the groups for the column to an array.
        ListViewGroup groupsArray[] = new ListViewGroup[groups.get_Count()];
        groups.get_Values().CopyTo(groupsArray, 0);
        // Sort the groups and add them to myListView.
        Array.Sort(groupsArray, new ListViewGroupSorter(
            myListView.get_Sorting()));
        myListView.get_Groups().AddRange(groupsArray);
    } //SetGroups

    // Creates a Hashtable object with one entry for each unique
    // subitem value (or initial letter for the parent item)
    // in the specified column.
    private Hashtable CreateGroupsTable(int column)
    {
        // Create a Hashtable object.
        Hashtable groups = new Hashtable();
        // Iterate through the items in myListView.
        for (int iCtr = 0; iCtr < myListView.get_Items().get_Count(); iCtr++) {
            ListViewItem item = myListView.get_Items().get_Item(iCtr);
            // Retrieve the text value for the column.
            String subItemText = item.get_SubItems().get_Item(column).get_Text();
            // Use the initial letter instead if it is the first column.
            if (column == 0) {
                subItemText = subItemText.Substring(0, 1);
            }
            // If the groups table does not already contain a group
            // for the subItemText value, add a new group using the 
            // subItemText value for the group header and Hashtable key.
            if (!(groups.Contains(subItemText))) {
                groups.Add(subItemText, new ListViewGroup(subItemText, 
                    HorizontalAlignment.Left));
            }
        }
        // Return the Hashtable object.
        return groups;
    } //CreateGroupsTable

    // Sorts ListViewGroup objects by header value.
    private class ListViewGroupSorter implements IComparer
    {
        private SortOrder order;

        // Stores the sort order.
        public ListViewGroupSorter(SortOrder theOrder)
        {
            order = theOrder;
        } //ListViewGroupSorter

        // Compares the groups by header value, using the saved sort
        // order to return the correct value.
        public int Compare(Object x, Object y)
        {
            int result = String.Compare(((ListViewGroup)x).get_Header(), 
                ((ListViewGroup)y).get_Header());
            if (order.Equals(SortOrder.Ascending)) {
                return result;
            }
            else {
                return -result;
            }
        } //Compare
    } //ListViewGroupSorter
} //ListViewGroupsExample 

System.Object
  System.Windows.Forms.ListViewGroupCollection
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.