ListView.SelectedListViewItemCollection ListView.SelectedListViewItemCollection ListView.SelectedListViewItemCollection ListView.SelectedListViewItemCollection Class

Definición

Representa la colección de elementos seleccionados en un control de vista de lista.Represents the collection of selected items in a list view control.

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

Ejemplos

En el ejemplo de código siguiente se SelectedItemsmuestra SelectedIndexChanged el uso de HeaderStyle los miembros, ListView.SelectedListViewItemCollection eventos y y la clase.The following code example demonstrates using the SelectedItems, SelectedIndexChanged event, and HeaderStyle members and the ListView.SelectedListViewItemCollection class. Para ejecutar este ejemplo, pegue el código siguiente en un formulario que contenga ListView un objeto ListView1 denominado y TextBox un TextBox1denominado.To run this example, paste the following code in a form that contains a ListView object named ListView1 and a TextBox named TextBox1. Llame al InitializeListView método desde el constructor del formulario o el Load controlador de eventos.Call the InitializeListView method from the form's constructor or the Load event handler. Este ejemplo requiere que el controlador de eventos esté asociado SelectedIndexChanged correctamente al evento.This example requires that the event handler is correctly associated with the SelectedIndexChanged event

// This method adds two columns to the ListView, setting the Text 
// and TextAlign, and Width properties of each ColumnHeader.  The 
// HeaderStyle property is set to NonClickable since the ColumnClick 
// event is not handled.  Finally the method adds ListViewItems and 
// SubItems to each column.
void InitializeListView()
{
   this->ListView1 = gcnew System::Windows::Forms::ListView;
   this->ListView1->BackColor = System::Drawing::SystemColors::Control;
   this->ListView1->Dock = System::Windows::Forms::DockStyle::Top;
   this->ListView1->Location = System::Drawing::Point( 0, 0 );
   this->ListView1->Name = "ListView1";
   this->ListView1->Size = System::Drawing::Size( 292, 130 );
   this->ListView1->TabIndex = 0;
   this->ListView1->View = System::Windows::Forms::View::Details;
   this->ListView1->MultiSelect = true;
   this->ListView1->HideSelection = false;
   this->ListView1->HeaderStyle = ColumnHeaderStyle::Nonclickable;
   ColumnHeader^ columnHeader1 = gcnew ColumnHeader;
   columnHeader1->Text = "Breakfast Item";
   columnHeader1->TextAlign = HorizontalAlignment::Left;
   columnHeader1->Width = 146;
   ColumnHeader^ columnHeader2 = gcnew ColumnHeader;
   columnHeader2->Text = "Price Each";
   columnHeader2->TextAlign = HorizontalAlignment::Center;
   columnHeader2->Width = 142;
   this->ListView1->Columns->Add( columnHeader1 );
   this->ListView1->Columns->Add( columnHeader2 );
   array<String^>^foodList = {"Juice","Coffee","Cereal & Milk","Fruit Plate","Toast & Jelly","Bagel & Cream Cheese"};
   array<String^>^foodPrice = {"1.09","1.09","2.19","2.49","1.49","1.49"};
   for ( int count = 0; count < foodList->Length; count++ )
   {
      ListViewItem^ listItem = gcnew ListViewItem( foodList[ count ] );
      listItem->SubItems->Add( foodPrice[ count ] );
      ListView1->Items->Add( listItem );

   }
   this->Controls->Add( ListView1 );
}
  // This method adds two columns to the ListView, setting the Text 
  // and TextAlign, and Width properties of each ColumnHeader.  The 
  // HeaderStyle property is set to NonClickable since the ColumnClick 
  // event is not handled.  Finally the method adds ListViewItems and 
  // SubItems to each column.
  private void InitializeListView()
  {
      this.ListView1 = new System.Windows.Forms.ListView();
      this.ListView1.BackColor = System.Drawing.SystemColors.Control;
      this.ListView1.Dock = System.Windows.Forms.DockStyle.Top;
      this.ListView1.Location = new System.Drawing.Point(0, 0);
      this.ListView1.Name = "ListView1";
      this.ListView1.Size = new System.Drawing.Size(292, 130);
      this.ListView1.TabIndex = 0;
      this.ListView1.View = System.Windows.Forms.View.Details;
      this.ListView1.MultiSelect = true;
      this.ListView1.HideSelection = false;
      this.ListView1.HeaderStyle = ColumnHeaderStyle.Nonclickable;
      
      ColumnHeader columnHeader1 = new ColumnHeader();
      columnHeader1.Text = "Breakfast Item";
      columnHeader1.TextAlign = HorizontalAlignment.Left;
      columnHeader1.Width = 146;

      ColumnHeader columnHeader2 = new ColumnHeader();
      columnHeader2.Text = "Price Each";
      columnHeader2.TextAlign = HorizontalAlignment.Center;
      columnHeader2.Width = 142;

      this.ListView1.Columns.Add(columnHeader1);
      this.ListView1.Columns.Add(columnHeader2);

      string[] foodList = new string[]{"Juice", "Coffee", 
          "Cereal & Milk", "Fruit Plate", "Toast & Jelly", 
          "Bagel & Cream Cheese"};
      string[] foodPrice = new string[]{"1.09", "1.09", "2.19", 
          "2.49", "1.49", "1.49"};
      
      for(int count=0; count < foodList.Length; count++)
      {
          ListViewItem listItem = new ListViewItem(foodList[count]);
          listItem.SubItems.Add(foodPrice[count]);
          ListView1.Items.Add(listItem);
      }
      this.Controls.Add(ListView1);
  }
  
' This method adds two columns to the ListView, setting the Text 
' and TextAlign, and Width properties of each ColumnHeader.  The 
' HeaderStyle property is set to NonClickable since the ColumnClick 
' event is not handled.  Finally the method adds ListViewItems and 
' SubItems to each column.
Private Sub InitializeListView()
    Me.ListView1 = New System.Windows.Forms.ListView
    Me.ListView1.BackColor = System.Drawing.SystemColors.Control
    Me.ListView1.Dock = System.Windows.Forms.DockStyle.Top
    Me.ListView1.Location = New System.Drawing.Point(0, 0)
    Me.ListView1.Name = "ListView1"
    Me.ListView1.Size = New System.Drawing.Size(292, 130)
    Me.ListView1.TabIndex = 0
    Me.ListView1.View = System.Windows.Forms.View.Details
    Me.ListView1.MultiSelect = True
    Me.ListView1.HideSelection = False
    ListView1.HeaderStyle = ColumnHeaderStyle.Nonclickable
    Dim columnHeader1 As New ColumnHeader
    With columnHeader1
        .Text = "Breakfast Item"
        .TextAlign = HorizontalAlignment.Left
        .Width = 146
    End With
    Dim columnHeader2 As New ColumnHeader
    With columnHeader2
        .Text = "Price Each"
        .TextAlign = HorizontalAlignment.Center
        .Width = 142
    End With

    Me.ListView1.Columns.Add(columnHeader1)
    Me.ListView1.Columns.Add(columnHeader2)
    Dim foodList() As String = New String() {"Juice", "Coffee", _
        "Cereal & Milk", "Fruit Plate", "Toast & Jelly", _
        "Bagel & Cream Cheese"}
    Dim foodPrice() As String = New String() {"1.09", "1.09", _
        "2.19", "2.49", "1.49", "1.49"}
    Dim count As Integer
    For count = 0 To foodList.Length - 1
        Dim listItem As New ListViewItem(foodList(count))
        listItem.SubItems.Add(foodPrice(count))
        ListView1.Items.Add(listItem)
    Next
    Me.Controls.Add(Me.ListView1)
End Sub
// Uses the SelectedItems property to retrieve and tally the price 
// of the selected menu items.
void ListView1_SelectedIndexChanged_UsingItems( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
   ListView::SelectedListViewItemCollection^ breakfast = this->ListView1->SelectedItems;
   double price = 0.0;
   System::Collections::IEnumerator^ myEnum = breakfast->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      ListViewItem^ item = safe_cast<ListViewItem^>(myEnum->Current);
      price += Double::Parse( item->SubItems[ 1 ]->Text );
   }

   // Output the price to TextBox1.
   TextBox1->Text = price.ToString();
}
// Uses the SelectedItems property to retrieve and tally the price 
// of the selected menu items.
private void ListView1_SelectedIndexChanged_UsingItems(
    object sender, System.EventArgs e)
{

    ListView.SelectedListViewItemCollection breakfast = 
        this.ListView1.SelectedItems;
    
    double price = 0.0;
    foreach ( ListViewItem item in breakfast )
    {
        price += Double.Parse(item.SubItems[1].Text);
    }

    // Output the price to TextBox1.
    TextBox1.Text = price.ToString();
}
' Uses the SelectedItems property to retrieve and tally the price 
' of the selected menu items.
Private Sub ListView1_SelectedIndexChanged_UsingItems _
    (ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles ListView1.SelectedIndexChanged

    Dim breakfast As ListView.SelectedListViewItemCollection = _
        Me.ListView1.SelectedItems
    Dim item As ListViewItem
    Dim price As Double = 0.0
    For Each item In breakfast
        price += Double.Parse(item.SubItems(1).Text)
    Next

    ' Output the price to TextBox1.
    TextBox1.Text = CType(price, String)
End Sub

Comentarios

Almacena los elementos seleccionados en un ListView control. ListView.SelectedListViewItemCollectionA ListView.SelectedListViewItemCollection stores the selected items in a ListView control. Los elementos almacenados en ListView.SelectedListViewItemCollection son elementos contenidos ListView.ListViewItemCollectionen.The items stored in the ListView.SelectedListViewItemCollection are items contained in the ListView.ListViewItemCollection. Almacena todos los elementos mostrados en ListViewel. ListView.ListViewItemCollectionThe ListView.ListViewItemCollection stores all items displayed in the ListView.

En la tabla siguiente se muestra un ejemplo de ListView.ListViewItemCollection cómo almacena los elementos ListView de, así como sus Estados de selección en un ListView control de ejemplo.The following table shows an example of how the ListView.ListViewItemCollection stores the items of the ListView as well as their selection states in an example ListView control.

ÍndiceIndex ElementoItem Estado de selección en ListViewSelection state in the ListView
00 Elemento1Item1 No seleccionadoUnselected
11 Item2Item2 SeleccionadoSelected
22 Item3Item3 No seleccionadoUnselected
33 Item4 (Item4 SeleccionadoSelected
44 Item5 (Item5 SeleccionadoSelected

Según el ListView.ListViewItemCollection ejemplo de la tabla anterior, en la tabla siguiente se muestra ListView.SelectedListViewItemCollection cómo aparecería.Based on the ListView.ListViewItemCollection example in the previous table, the following table demonstrates how the ListView.SelectedListViewItemCollection would appear.

ÍndiceIndex Elemento seleccionado en el ListViewItemCollectionSelected item in the ListViewItemCollection
00 Item2Item2
11 Item4 (Item4
22 Item5 (Item5

Puede utilizar las propiedades y los métodos de esta clase para realizar diversas tareas con la colección.You can use the properties and methods of this class to perform a variety of tasks with the collection. El Contains método le permite determinar si un elemento de la ListView.ListViewItemCollection clase ListView.SelectedListViewItemCollectiones un miembro de.The Contains method enables you to determine whether an item from the ListView.ListViewItemCollection class is a member of the ListView.SelectedListViewItemCollection. Una vez que sepa que el elemento está en la colección, puede utilizar el IndexOf método para determinar la posición del elemento ListView.SelectedListViewItemCollectionen.Once you know that the item is in the collection, you can use the IndexOf method to determine the position of the item in the ListView.SelectedListViewItemCollection.

Constructores

ListView.SelectedListViewItemCollection(ListView) ListView.SelectedListViewItemCollection(ListView) ListView.SelectedListViewItemCollection(ListView) ListView.SelectedListViewItemCollection(ListView)

Inicializa una nueva instancia de la clase ListView.SelectedListViewItemCollection.Initializes a new instance of the ListView.SelectedListViewItemCollection class.

Propiedades

Count Count Count Count

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

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

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

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

Obtiene el elemento en el índice especificado de la colección.Gets the item at the specified index within the collection.

Item[String] Item[String] Item[String] Item[String]

Obtiene un elemento de la colección que tiene la clave especificada.Gets an item with the specified key from the collection.

Métodos

Clear() Clear() Clear() Clear()

Quita todos los elementos de la colección.Removes all items from the collection.

Contains(ListViewItem) Contains(ListViewItem) Contains(ListViewItem) Contains(ListViewItem)

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

ContainsKey(String) ContainsKey(String) ContainsKey(String) ContainsKey(String)

Determina si hay un elemento con la clave especificada en la colección.Determines whether an item with the specified key is contained in the collection.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

Copia toda la colección en una matriz existente, en un lugar especificado de la matriz.Copies the entire collection into an existing array at a specified location within the array.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Devuelve un enumerador que se puede utilizar para recorrer en iteración en la colección de elementos seleccionados.Returns an enumerator that can be used to iterate through the selected item collection.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
IndexOf(ListViewItem) IndexOf(ListViewItem) IndexOf(ListViewItem) IndexOf(ListViewItem)

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

IndexOfKey(String) IndexOfKey(String) IndexOfKey(String) IndexOfKey(String)

Devuelve el índice de la primera aparición del elemento que tiene la clave especificada.Returns the index of the first occurrence of the item with the specified key.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)

Implementaciones de interfaz explícitas

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized 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 ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

Obtiene un objeto que puede utilizarse para sincronizar el acceso a la colección de controles.Gets an object that can be used to synchronize access to the collection of controls.

IList.Add(Object) IList.Add(Object) IList.Add(Object) IList.Add(Object)

Agrega un elemento a la colección.Adds an item to the collection.

IList.Contains(Object) IList.Contains(Object) IList.Contains(Object) IList.Contains(Object)

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

IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object)

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

IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object)

Inserta un elemento en el índice especificado de la colección.Inserts an item into the collection at a specified index.

IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize 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.Item[Int32] IList.Item[Int32] IList.Item[Int32] IList.Item[Int32]

Obtiene o establece un objeto de la colección.Gets or sets an object from the collection.

IList.Remove(Object) IList.Remove(Object) IList.Remove(Object) IList.Remove(Object)

Quita la primera aparición de un elemento especificado de la colección.Removes the first occurrence of a specified item from the collection.

IList.RemoveAt(Int32) IList.RemoveAt(Int32) IList.RemoveAt(Int32) IList.RemoveAt(Int32)

Quita un elemento de la colección en un índice especificado.Removes an item from the collection at a specified index.

Métodos de extensión

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) 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) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) 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) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

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

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

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

Se aplica a