ListViewGroupCollection Clase

Definición

Representa la colección de grupos dentro de un control ListView.Represents the collection of groups within a ListView control.

public ref class ListViewGroupCollection : System::Collections::IList
[System.ComponentModel.ListBindable(false)]
public class ListViewGroupCollection : System.Collections.IList
type ListViewGroupCollection = class
    interface IList
    interface ICollection
    interface IEnumerable
Public Class ListViewGroupCollection
Implements IList
Herencia
ListViewGroupCollection
Atributos
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra cómo usar la característica de agrupación ListView para organizar elementos por valor de subelemento en la vista de detalles.The following example demonstrates how to use the ListView grouping feature to organize items by subitem value in the details view. Esta forma de agrupación es similar a la agrupación que se usa en el explorador de Windows.This form of grouping is similar to the grouping used in Windows Explorer. En el ejemplo, los grupos se crean dinámicamente.In the example, the groups are created dynamically. Para cada columna de subelemento, se crea un grupo para cada valor de subelemento único.For each subitem column, one group is created for each unique subitem value. En el caso de la columna elemento primario, se crea un grupo para cada letra inicial única.For the parent item column, one group is created for each unique initial letter. Al hacer clic en el encabezado de una columna, se ordenan los elementos de los grupos creados para esa columna.Clicking the header of a column sorts the items into the groups created for that column. Al hacer clic en el mismo encabezado de columna, se invierte el orden de los grupos.Clicking the same column header again reverses the order of the groups.

#using <mscorlib.dll>
#using <System.Drawing.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Collections; 
using namespace System::Windows::Forms;

public ref class ListViewGroupsExample : public Form
{
private:
   ListView^ myListView;
   bool isRunningXPOrLater;

   // Declare a Hashtable array in which to store the groups.
   array<Hashtable^>^ groupTables;

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

public:
   ListViewGroupsExample()
   {
      groupColumn = 0;
      // Initialize myListView.
      myListView = gcnew ListView();
      myListView->Dock = DockStyle::Fill;
      myListView->View = View::Details;
      myListView->Sorting = SortOrder::Ascending;

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

      // Add the column headers to myListView.

      array<ColumnHeader^>^ temp0 = {columnHeader0, columnHeader1, columnHeader2};
      myListView->Columns->AddRange(temp0);

      // Add a handler for the ColumnClick event.
      myListView->ColumnClick += 
         gcnew ColumnClickEventHandler(this, &ListViewGroupsExample::myListView_ColumnClick);

      // Create items and add them to myListView.

      array<String^>^ temp1 = {"Programming Windows", "Petzold, Charles", "1998"};
      ListViewItem^ item0 = gcnew ListViewItem( temp1 );

      array<String^>^ temp2 = {"Code: The Hidden Language of Computer Hardware and Software",
         "Petzold, Charles", "2000"};
      ListViewItem^ item1 = gcnew ListViewItem( temp2 );

      array<String^>^ temp3 = {"Programming Windows with C#", "Petzold, Charles", "2001"};
      ListViewItem^ item2 = gcnew ListViewItem( temp3 );

      array<String^>^ temp4 = {"Coding Techniques for Microsoft Visual Basic .NET",
         "Connell, John", "2001"};
      ListViewItem^ item3 = gcnew ListViewItem( temp4 );

      array<String^>^ temp5 = {"C# for Java Developers", "Jones, Allen & Freeman, Adam",
         "2002"};
      ListViewItem^ item4 = gcnew ListViewItem( temp5 );

      array<String^>^ temp6 = {"Microsoft .NET XML Web Services Step by Step",
         "Jones, Allen & Freeman, Adam", "2002"};
      ListViewItem^ item5 = gcnew ListViewItem( temp6 );

      array<ListViewItem^>^ temp7 = {item0, item1, item2, item3, item4, item5};
      myListView->Items->AddRange( temp7 );

      // Determine whether Windows XP or a later 
      // operating system is present.
      isRunningXPOrLater = false;

      if (System::Environment::OSVersion->Version->Major > 5 ||
         ( System::Environment::OSVersion->Version->Major == 5 &&
         System::Environment::OSVersion->Version->Minor >= 1) )
      {
         isRunningXPOrLater = true;
      }

      if (isRunningXPOrLater)
      {
         // Create the groupsTable array and populate it with one 
         // hash table for each column.
         groupTables = gcnew array<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 = System::Drawing::Size(550, 330);
      this->Text = "ListView Groups Example";
   }

   // 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 = dynamic_cast<Hashtable^>(groupTables[column]);

      // Copy the groups for the column to an array.
      array<ListViewGroup^>^ groupsArray = gcnew array<ListViewGroup^>(groups->Count);
      groups->Values->CopyTo(groupsArray, 0);

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

      // Iterate through the items in myListView, assigning each 
      // one to the appropriate group.
      IEnumerator^ myEnum = myListView->Items->GetEnumerator();
      while (myEnum->MoveNext())
      {
         ListViewItem^ item = safe_cast<ListViewItem^>(myEnum->Current);
         // 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 = dynamic_cast<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 = gcnew Hashtable();

      // Iterate through the items in myListView.
      IEnumerator^ myEnum1 = myListView->Items->GetEnumerator();
      while (myEnum1->MoveNext())
      {
         ListViewItem^ item = safe_cast<ListViewItem^>(myEnum1->Current);
         // 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, gcnew ListViewGroup(subItemText, 
               HorizontalAlignment::Left) );
         }
      }

      // Return the Hashtable object.
      return groups;
   }

   // Sorts ListViewGroup objects by header value.
   ref class ListViewGroupSorter : public 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.
      virtual int Compare(Object^ x, Object^ y)
      {
         int result = String::Compare(
            (dynamic_cast<ListViewGroup^>(x))->Header,
            (dynamic_cast<ListViewGroup^>(y))->Header
            );
         if (order == SortOrder::Ascending)
         {
            return result;
         }
         else 
         {
            return -result;
         }
      }
   };
};

[STAThread]
int main() 
{
   Application::EnableVisualStyles();
   Application::Run(gcnew ListViewGroupsExample());
}
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;
            }
        }
    }

}
Imports System.Collections
Imports System.Windows.Forms

Public Class ListViewGroupsExample
    Inherits Form

    Private myListView As ListView

    ' Determine whether Windows XP or a later
    ' operating system is present.
    Private isRunningXPOrLater As Boolean = _
        OSFeature.Feature.IsPresent(OSFeature.Themes)
    
    ' Declare a Hashtable array in which to store the groups.
    Private groupTables() As Hashtable
    
    ' Declare a variable to store the current grouping column.
    Private groupColumn As Integer = 0
    
    Public Sub New()
        ' Initialize myListView.
        myListView = New ListView()
        myListView.Dock = DockStyle.Fill
        myListView.View = View.Details
        myListView.Sorting = SortOrder.Ascending
        
        ' Create and initialize column headers for myListView.
        Dim columnHeader0 As New ColumnHeader()
        columnHeader0.Text = "Title"
        columnHeader0.Width = -1
        Dim columnHeader1 As New ColumnHeader()
        columnHeader1.Text = "Author"
        columnHeader1.Width = -1
        Dim columnHeader2 As 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.
        AddHandler myListView.ColumnClick, AddressOf myListView_ColumnClick
        
        ' Create items and add them to myListView.
        Dim item0 As New ListViewItem( New String() _
            {"Programming Windows", _
            "Petzold, Charles", _
            "1998"} )
        Dim item1 As New ListViewItem( New String() _
            {"Code: The Hidden Language of Computer Hardware and Software", _
            "Petzold, Charles", _
            "2000"} )
        Dim item2 As New ListViewItem( New String() _
            {"Programming Windows with C#", _
            "Petzold, Charles", _
            "2001"} )
        Dim item3 As New ListViewItem( New String() _
            {"Coding Techniques for Microsoft Visual Basic .NET", _
            "Connell, John", _
            "2001"} )
        Dim item4 As New ListViewItem( New String() _
            {"C# for Java Developers", _
            "Jones, Allen / Freeman, Adam", _
            "2002"} )
        Dim item5 As 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) {}
            Dim column As Integer
            For column = 0 To myListView.Columns.Count - 1
                ' Create a hash table containing all the groups 
                ' needed for a single column.
                groupTables(column) = CreateGroupsTable(column)
            Next column
            
            ' Start with the groups created for the Title column.
            SetGroups(0)
        End If
        
        ' Initialize the form.
        Me.Controls.Add(myListView)
        Me.Size = New System.Drawing.Size(550, 330)
        Me.Text = "ListView Groups Example"
    End Sub
    
    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New ListViewGroupsExample())
    End Sub
    
    ' Groups the items using the groups created for the clicked 
    ' column.
    Private Sub myListView_ColumnClick( _
        sender As Object, e As ColumnClickEventArgs)

        ' Set the sort order to ascending when changing
        ' column groups; otherwise, reverse the sort order.
        If myListView.Sorting = SortOrder.Descending OrElse _
            isRunningXPOrLater And e.Column <> groupColumn Then
            myListView.Sorting = SortOrder.Ascending
        Else
            myListView.Sorting = SortOrder.Descending
        End If
        groupColumn = e.Column
        
        ' Set the groups to those created for the clicked column.
        If isRunningXPOrLater Then
            SetGroups(e.Column)
        End If
    End Sub
    
    ' Sets myListView to the groups created for the specified column.
    Private Sub SetGroups(column As Integer)
        ' Remove the current groups.
        myListView.Groups.Clear()
        
        ' Retrieve the hash table corresponding to the column.
        Dim groups As Hashtable = CType(groupTables(column), Hashtable)
        
        ' Copy the groups for the column to an array.
        Dim groupsArray(groups.Count - 1) As ListViewGroup
        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.
        Dim item As ListViewItem
        For Each item In myListView.Items
            ' Retrieve the subitem text corresponding to the column.
            Dim subItemText As String = item.SubItems(column).Text
            
            ' For the Title column, use only the first letter.
            If column = 0 Then
                subItemText = subItemText.Substring(0, 1)
            End If 

            ' Assign the item to the matching group.
            item.Group = CType(groups(subItemText), ListViewGroup)
        Next item
    End Sub

    ' Creates a Hashtable object with one entry for each unique
    ' subitem value (or initial letter for the parent item)
    ' in the specified column.
    Private Function CreateGroupsTable(column As Integer) As Hashtable
        ' Create a Hashtable object.
        Dim groups As New Hashtable()
        
        ' Iterate through the items in myListView.
        Dim item As ListViewItem
        For Each item In myListView.Items
            ' Retrieve the text value for the column.
            Dim subItemText As String = item.SubItems(column).Text
            
            ' Use the initial letter instead if it is the first column.
            If column = 0 Then
                subItemText = subItemText.Substring(0, 1)
            End If 

            ' 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 Not groups.Contains(subItemText) Then
                groups.Add( subItemText, New ListViewGroup(subItemText, _
                    HorizontalAlignment.Left) )
            End If
        Next item
        
        ' Return the Hashtable object.
        Return groups
    End Function 'CreateGroupsTable

    ' Sorts ListViewGroup objects by header value.
    Private Class ListViewGroupSorter
        Implements IComparer 
        
        Private order As SortOrder
        
        ' Stores the sort order.
        Public Sub New(theOrder As SortOrder)
            order = theOrder
        End Sub
        
        ' Compares the groups by header value, using the saved sort
        ' order to return the correct value.
        Public Function Compare(x As Object, y As Object) As Integer _
            Implements IComparer.Compare
            Dim result As Integer = String.Compare( _
                CType(x, ListViewGroup).Header, _
                CType(y, ListViewGroup).Header )
            If order = SortOrder.Ascending Then
                Return result
            Else
                Return -result
            End If
        End Function 'Compare
    End Class

End Class

Comentarios

Use la propiedad ListView.Groups para obtener el ListViewGroupCollection asociado a un control ListView.Use the ListView.Groups property to get the ListViewGroupCollection associated with a ListView control. Esta colección contiene los objetos ListViewGroup que representan los grupos mostrados en el control cuando la propiedad ListView.View está establecida en un valor distinto de View.List.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. Cualquier elemento que no esté asignado a un grupo aparecerá en el grupo predeterminado, que tiene la etiqueta de encabezado "DefaultGroup @ no__t-0".Any items that are not assigned to a group will appear in the default group, which has the header label "DefaultGroup{0}". El grupo predeterminado no está incluido en la colección ListView.Groups y no se puede modificar.The default group is not contained in the ListView.Groups collection, and cannot be altered. Es principalmente útil en la depuración para asegurarse de que todos los elementos se han agregado correctamente a los grupos.It is primarily useful in debugging to ensure that all items have been properly added to groups. Si no hay ningún grupo en la colección ListView.Groups, la característica de agrupación está deshabilitada.If there are no groups in the ListView.Groups collection, the grouping feature is disabled.

Use el método Add para agregar un solo grupo a la colección.Use the Add method to add a single group to the collection. Use el método Insert para agregar un grupo en un índice determinado de la colección.Use the Insert method to add a group at a particular index within the collection. Para quitar un grupo, use el método Remove.To remove a group, use the Remove method. Use el método RemoveAt para quitar el grupo de un índice determinado.Use the RemoveAt method to remove the group at a particular index.

No se puede Agregar un ListViewGroup a la colección más de una vez.You cannot add a ListViewGroup to the collection more than once. Para cambiar la posición de un grupo dentro de la colección, primero debe quitarse de la colección y, a continuación, insertarse en la ubicación deseada.To reposition a group within the collection, it must first be removed from the collection, and then inserted at the desired location. Use el método Contains para determinar si un grupo determinado ya está en la colección.Use the Contains method to determine whether a particular group is already in the collection. Para recuperar el índice de un grupo dentro de la colección, use el método IndexOf.To retrieve the index of a group within the collection, use the IndexOf method. Puede obtener o establecer el grupo en un índice determinado con el indizador Item[Int32].You can get or set the group at a particular index with the Item[Int32] indexer.

Use el método AddRange para agregar varios grupos a la colección.Use the AddRange method to add multiple groups to the collection. Puede agregar varios grupos como una matriz de grupos o como ListViewGroupCollection que se recuperan a través de la propiedad ListView.Groups de otro control ListView.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 el método Clear para quitar todos los grupos de la colección.Use the Clear method to remove all the groups from the collection.

Nota

Los métodos Remove, RemoveAt y Clear quitan los grupos de la colección, pero no quitan los elementos del control ListView.The Remove, RemoveAt, and Clear methods remove groups from the collection, but do not remove any items from the ListView control. Si no hay ningún grupo en la colección ListView.Groups, la característica de agrupación está deshabilitada y todos los elementos del control se muestran normalmente.If there are no groups in the ListView.Groups collection, the grouping feature is disabled and all items in the control are displayed normally.

Los métodos AddRange y Clear son útiles cuando se desea proporcionar varias maneras de agrupar los elementos en un control ListView.The AddRange and Clear methods are useful when you want to provide multiple ways to group the items in a ListView control. Para ello, cree varias matrices de grupos.To do this, create multiple group arrays. Para cambiar la agrupación, use primero el método Clear para quitar todos los grupos de la colección y, a continuación, use el método AddRange para agregar la siguiente matriz de grupos que se va a mostrar.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 el método CopyTo para copiar los grupos de una colección en una matriz compatible a partir de un índice especificado.Use the CopyTo method to copy the groups in a collection to a compatible array starting at a specified index. Esto resulta útil, por ejemplo, cuando desea ordenar los grupos de la colección mediante el método Array.Sort.This is useful, for example, when you want to sort the groups in the collection using the Array.Sort method. Para ello, copie los grupos en una matriz compatible y, a continuación, ordene la matriz.To do this, copy the groups into a compatible array, then sort the array. A continuación, use el método Clear para quitar todos los grupos de la colección y, a continuación, use el método AddRange para volver a agregar la matriz ordenada a la colección.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 la propiedad Count para determinar el número de grupos que hay en la colección.Use the Count property to determine how many groups are in the collection. Para recorrer en iteración la colección, use el IEnumerator devuelto por el método GetEnumerator.To iterate through the collection, use the IEnumerator returned from the GetEnumerator method.

Nota

La característica de agrupación solo está disponible en Windows XP y en la familia de Windows Server 2003 cuando la aplicación llama al método Application.EnableVisualStyles.The grouping feature is available only on Windows XP and the Windows Server 2003 family when your application calls the Application.EnableVisualStyles method. En los sistemas operativos anteriores, se omitirá cualquier código relacionado con los grupos y los grupos no aparecerán.On earlier operating systems, any code relating to groups will be ignored and the groups will not appear. Como resultado, cualquier código que dependa de la característica de agrupación podría no funcionar correctamente.As a result, any code that depends on the grouping feature might not work correctly. Es posible que desee incluir una prueba que determine si la característica de agrupación está disponible y proporcionar una funcionalidad alternativa cuando no está disponible.You might want to include a test that determines whether the grouping feature is available, and provide alternate functionality when it is unavailable. Por ejemplo, puede que desee proporcionar una ordenación alternativa cuando se ejecuta en sistemas operativos que no admiten la ordenación por grupo.For example, you might want to provide alternate sorting when running on operating systems that do not support sorting by group.

La característica de marca de inserción la proporciona la misma biblioteca que proporciona la característica temas del sistema operativo.The insertion mark feature is provided by the same library that provides the operating system themes feature. Para comprobar la disponibilidad de esta biblioteca, llame a la sobrecarga del método FeatureSupport.IsPresent(Object) y pase el valor de OSFeature.Themes.To check for the availability of this library, call the FeatureSupport.IsPresent(Object) method overload and pass in the OSFeature.Themes value.

Propiedades

Count

Obtiene el número de grupos de la colección.Gets the number of groups in the collection.

Item[Int32]

Obtiene o establece el objeto ListViewGroup en el índice especificado de la colección.Gets or sets the ListViewGroup at the specified index within the collection.

Item[String]

Obtiene o establece el ListViewGroup que tiene el valor de la propiedad Name especificado.Gets or sets the ListViewGroup with the specified Name property value.

Métodos

Add(ListViewGroup)

Agrega el ListViewGroup especificado a la colección.Adds the specified ListViewGroup to the collection.

Add(String, String)

Agrega un nueva instancia de ListViewGroup a la colección mediante los valores especificados para inicializar las propiedades Name y Header.Adds a new ListViewGroup to the collection using the specified values to initialize the Name and Header properties.

AddRange(ListViewGroup[])

Agrega una matriz de grupos a la colección.Adds an array of groups to the collection.

AddRange(ListViewGroupCollection)

Agrega a la colección los grupos de un ListViewGroupCollection existente.Adds the groups in an existing ListViewGroupCollection to the collection.

Clear()

Quita todos los grupos de la colección.Removes all groups from the collection.

Contains(ListViewGroup)

Determina si el grupo especificado se encuentra en la colección.Determines whether the specified group is located in the collection.

CopyTo(Array, Int32)

Copia los grupos de la colección en un control Array unidimensional compatible, empezando en el índice especificado de la matriz de destino.Copies the groups in the collection to a compatible one-dimensional Array, starting at the specified index of the target array.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
GetEnumerator()

Devuelve un enumerador utilizado para recorrer en iteración la colección.Returns an enumerator used to iterate through the collection.

GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
IndexOf(ListViewGroup)

Devuelve el índice del ListViewGroup especificado en la colección.Returns the index of the specified ListViewGroup within the collection.

Insert(Int32, ListViewGroup)

Inserta la clase ListViewGroup especificada en el índice especificado de la colección.Inserts the specified ListViewGroup into the collection at the specified index.

MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
Remove(ListViewGroup)

Quita el objeto ListViewGroup especificado de la colección.Removes the specified ListViewGroup from the collection.

RemoveAt(Int32)

Quita el ListViewGroup de la colección en el índice especificado.Removes the ListViewGroup at the specified index within the collection.

ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)

Implementaciones de interfaz explícitas

ICollection.IsSynchronized

Obtiene un valor que indica si el acceso a la colección está sincronizado (es seguro para la ejecución de subprocesos).Gets a value indicating whether access to the collection is synchronized (thread safe).

ICollection.SyncRoot

Obtiene un objeto que se puede utilizar para sincronizar el acceso a la colección.Gets an object that can be used to synchronize access to the collection.

IList.Add(Object)

Agrega un nuevo objeto ListViewGroup a la colección ListViewGroupCollection.Adds a new ListViewGroup to the ListViewGroupCollection.

IList.Contains(Object)

Determina si el valor especificado se encuentra en la colección.Determines whether the specified value is located in the collection.

IList.IndexOf(Object)

Devuelve el índice en la colección del valor especificado.Returns the index within the collection of the specified value.

IList.Insert(Int32, Object)

Inserta un control ListViewGroup en ListViewGroupCollection.Inserts a ListViewGroup into the ListViewGroupCollection.

IList.IsFixedSize

Obtiene un valor que indica si la colección tiene un tamaño fijo.Gets a value indicating whether the collection has a fixed size.

IList.IsReadOnly

Obtiene un valor que indica si la colección es de solo lectura.Gets a value indicating whether the collection is read-only.

IList.Item[Int32]

Obtiene o establece el objeto ListViewGroup en el índice especificado de la colección.Gets or sets the ListViewGroup at the specified index within the collection.

IList.Remove(Object)

Quita el objeto ListViewGroup de la colección ListViewGroupCollection.Removes the ListViewGroup from the ListViewGroupCollection.

Métodos de extensión

Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita la paralelización de una consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

Se aplica a

Consulte también: