Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.

Classe ListViewGroup


Representa um grupo de itens exibidos em um controle ListView.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)


public sealed class ListViewGroup : ISerializable


Inicializa uma nova instância de ListViewGroup classe usando o texto de cabeçalho padrão de "ListViewGroup" e o padrão de cabeçalho à esquerda.


Inicializa uma nova instância do ListViewGroup classe usando o valor especificado para inicializar o Header propriedade e usando o padrão de alinhamento do cabeçalho à esquerda.

System_CAPS_pubmethodListViewGroup(String, HorizontalAlignment)

Inicializa uma nova instância de ListViewGroup classe usando o texto de cabeçalho especificado e o alinhamento de cabeçalho especificado.

System_CAPS_pubmethodListViewGroup(String, String)

Inicializa uma nova instância do ListViewGroup classe usando os valores especificados para inicializar o Name e Header Propriedades.


Obtém ou define o texto do cabeçalho para o grupo.


Obtém ou define o alinhamento do texto do cabeçalho de grupo.


Obtém uma coleção que contém todos os itens associados a esse grupo.


Obtém o ListView controle que contém este grupo.


Obtém ou define o nome do grupo.


Obtém ou define o objeto que contém dados sobre o grupo.


Verifica se o objeto especificado é igual ao objeto atual. (Herdado de Object.)


Serve como a função de hash padrão.(Herdado de Object.)


Obtém o Type da instância atual.(Herdado de Object.)


Retorna uma string que representa o objeto atual.(Substitui o Object.ToString().)

System_CAPS_pubinterfaceSystem_CAPS_privmethodISerializable.GetObjectData(SerializationInfo, StreamingContext)

Preenche um SerializationInfo com os dados necessários para serializar o objeto de destino.

The T:System.Windows.Forms.ListView grouping feature lets you create visual groups of logically related T:System.Windows.Forms.ListView items. Each group consists of a text-based header followed by a horizontal line and the items assigned to that group. You can align the header text to the left, right, or center of the control. Any groups assigned to a T:System.Windows.Forms.ListView control appear whenever the P:System.Windows.Forms.ListView.View property is set to a value other than F:System.Windows.Forms.View.List.

ListView groups help your users find the items they are looking for by separating the items into useful categories. You can create whatever categories you need. One typical way to group the items is by the way they are sorted. For example, you can group the items by the initial letter of the item name when they are sorted alphabetically, or by subitems such as type or date when the list is sorted by clicking a column header in the details view. Windows Explorer uses this type of grouping.

To use the grouping feature, add one or more T:System.Windows.Forms.ListViewGroup objects to the P:System.Windows.Forms.ListView.Groups collection of a T:System.Windows.Forms.ListView control. Set the group header text and header alignment in the M:System.Windows.Forms.ListViewGroup.#ctor constructor, or set them using the P:System.Windows.Forms.ListViewGroup.Header and P:System.Windows.Forms.ListViewGroup.HeaderAlignment properties.

You can assign an item to a group by specifying the group in the M:System.Windows.Forms.ListViewItem.#ctor constructor, by setting the P:System.Windows.Forms.ListViewItem.Group property, or by directly adding the item to the P:System.Windows.Forms.ListViewGroup.Items collection of a group. All items should be assigned to groups before they are displayed. 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 P:System.Windows.Forms.ListView.Groups collection, and cannot be altered. It is primarily useful in debugging to ensure that all items have been properly added to groups.

An item can only be in one group at a time. You can change the group to which an item belongs by setting the P:System.Windows.Forms.ListViewItem.Group property at run time or by adding it to the P:System.Windows.Forms.ListViewGroup.Items collection of another group, which automatically removes it from the previous group.


The insertion mark feature is disabled when using groups. This is because the grouping feature orders items by group membership, while the insertion mark feature is used with drag-and-drop repositioning in a T:System.Windows.Forms.ListView control that does not already order its items.


ListView groups are 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 M:System.Windows.Forms.FeatureSupport.IsPresent(System.Object) method overload and pass in the F:System.Windows.Forms.OSFeature.Themes value.

The following code example demonstrates how to use the T:System.Windows.Forms.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 = 

    // 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"} );
            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.

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

    static void Main() 
        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;
            myListView.Sorting = SortOrder.Descending;
        groupColumn = e.Column;

        // Set the groups to those created for the clicked column.
        if (isRunningXPOrLater)

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

        // 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));

        // 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(
            if (order == SortOrder.Ascending)
                return result;
                return -result;


.NET Framework
Disponível desde 2.0

Quaisquer membros estáticos públicos ( Compartilhado no Visual Basic) desse tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Retornar ao início