ListBox.ObjectCollection ListBox.ObjectCollection ListBox.ObjectCollection ListBox.ObjectCollection Class

Definición

Representa la colección de elementos de un ListBox.Represents the collection of items in a ListBox.

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

Ejemplos

En el ejemplo de código siguiente se muestra un ListBox dibujado por el DrawMode propietario estableciendo la OwnerDrawVariable propiedad en el valor DrawItem y MeasureItem controlando los eventos y.The following code example demonstrates an owner-drawn ListBox by setting the DrawMode property to the OwnerDrawVariable value and handling the DrawItem and MeasureItem events. También se muestra cómo establecer BorderStyle las ScrollAlwaysVisible propiedades y y cómo AddRange utilizar el método.It also demonstrates setting the BorderStyle and ScrollAlwaysVisible properties and using the AddRange method.

Para ejecutar este ejemplo, péguelo en un formulario vacío que importe el System.Drawing espacio de nombres y el espacio de System.Windows.Forms nombres.To run this example, paste it into an empty form that imports the System.Drawing namespace and the System.Windows.Forms namespace. Llame InitializeOwnerDrawnListBox a desde el constructor o Load método del formulario.Call InitializeOwnerDrawnListBox from the form's constructor or Load method.

internal:
   System::Windows::Forms::ListBox^ ListBox1;

private:
   void InitializeOwnerDrawnListBox()
   {
      this->ListBox1 = gcnew System::Windows::Forms::ListBox;
      
      // Set the location and size.
      ListBox1->Location = Point(20,20);
      ListBox1->Size = System::Drawing::Size( 240, 240 );
      
      // Populate the ListBox.ObjectCollection property 
      // with several strings, using the AddRange method.
      array<Object^>^temp0 = {"System.Windows.Forms","System.Drawing","System.Xml","System.Net","System.Runtime.Remoting","System.Web"};
      this->ListBox1->Items->AddRange( temp0 );
      
      // Turn off the scrollbar.
      ListBox1->ScrollAlwaysVisible = false;
      
      // Set the border style to a single, flat border.
      ListBox1->BorderStyle = BorderStyle::FixedSingle;
      
      // Set the DrawMode property to the OwnerDrawVariable value. 
      // This means the MeasureItem and DrawItem events must be 
      // handled.
      ListBox1->DrawMode = DrawMode::OwnerDrawVariable;
      ListBox1->MeasureItem += gcnew MeasureItemEventHandler( this, &Form1::ListBox1_MeasureItem );
      ListBox1->DrawItem += gcnew DrawItemEventHandler( this, &Form1::ListBox1_DrawItem );
      this->Controls->Add( this->ListBox1 );
   }

   // Handle the DrawItem event for an owner-drawn ListBox.
   void ListBox1_DrawItem( Object^ /*sender*/, DrawItemEventArgs^ e )
   {
      // If the item is the selected item, then draw the rectangle
      // filled in blue. The item is selected when a bitwise And  
      // of the State property and the DrawItemState.Selected 
      // property is true.
      if ( (e->State & DrawItemState::Selected) == DrawItemState::Selected )
      {
         e->Graphics->FillRectangle( Brushes::CornflowerBlue, e->Bounds );
      }
      else
      {
         
         // Otherwise, draw the rectangle filled in beige.
         e->Graphics->FillRectangle( Brushes::Beige, e->Bounds );
      }
      
      // Draw a rectangle in blue around each item.
      e->Graphics->DrawRectangle( Pens::Blue, e->Bounds );
      
      // Draw the text in the item.
      e->Graphics->DrawString( ListBox1->Items[ e->Index ]->ToString(), this->Font, Brushes::Black, (float)e->Bounds.X, (float)e->Bounds.Y );
      
      // Draw the focus rectangle around the selected item.
      e->DrawFocusRectangle();
   }


   // Handle the MeasureItem event for an owner-drawn ListBox.
   void ListBox1_MeasureItem( Object^ sender, MeasureItemEventArgs^ e )
   {
      
      // Cast the sender object back to ListBox type.
      ListBox^ theListBox = dynamic_cast<ListBox^>(sender);
      
      // Get the string contained in each item.
      String^ itemString = dynamic_cast<String^>(theListBox->Items[ e->Index ]);
      
      // Split the string at the " . "  character.
      array<Char>^temp1 = {'.'};
      array<String^>^resultStrings = itemString->Split( temp1 );
      
      // If the string contains more than one period, increase the 
      // height by ten pixels; otherwise, increase the height by 
      // five pixels.
      if ( resultStrings->Length > 2 )
      {
         e->ItemHeight += 10;
      }
      else
      {
         e->ItemHeight += 5;
      }
   }
internal System.Windows.Forms.ListBox ListBox1;

private void InitializeOwnerDrawnListBox()
{
	this.ListBox1 = new System.Windows.Forms.ListBox();

	// Set the location and size.
	ListBox1.Location = new Point(20, 20);
	ListBox1.Size = new Size(240, 240);

	// Populate the ListBox.ObjectCollection property 
	// with several strings, using the AddRange method.
	this.ListBox1.Items.AddRange(new object[]{"System.Windows.Forms", 
		"System.Drawing", "System.Xml", "System.Net", "System.Runtime.Remoting", 
		"System.Web"});

	// Turn off the scrollbar.
	ListBox1.ScrollAlwaysVisible = false;

	// Set the border style to a single, flat border.
	ListBox1.BorderStyle = BorderStyle.FixedSingle;

	// Set the DrawMode property to the OwnerDrawVariable value. 
	// This means the MeasureItem and DrawItem events must be 
	// handled.
	ListBox1.DrawMode = DrawMode.OwnerDrawVariable;
	ListBox1.MeasureItem += 
		new MeasureItemEventHandler(ListBox1_MeasureItem);
	ListBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
	this.Controls.Add(this.ListBox1);
	
}


// Handle the DrawItem event for an owner-drawn ListBox.
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{

	// If the item is the selected item, then draw the rectangle
	// filled in blue. The item is selected when a bitwise And  
	// of the State property and the DrawItemState.Selected 
	// property is true.
	if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
	{
		e.Graphics.FillRectangle(Brushes.CornflowerBlue, e.Bounds);
	}
	else
	{
		// Otherwise, draw the rectangle filled in beige.
		e.Graphics.FillRectangle(Brushes.Beige, e.Bounds);
	}

	// Draw a rectangle in blue around each item.
	e.Graphics.DrawRectangle(Pens.Blue, e.Bounds);

	// Draw the text in the item.
	e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(),
		this.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y);

	// Draw the focus rectangle around the selected item.
	e.DrawFocusRectangle();
}

// Handle the MeasureItem event for an owner-drawn ListBox.
private void ListBox1_MeasureItem(object sender, 
	MeasureItemEventArgs e)
{

	// Cast the sender object back to ListBox type.
	ListBox theListBox = (ListBox) sender;

	// Get the string contained in each item.
	string itemString = (string) theListBox.Items[e.Index];

	// Split the string at the " . "  character.
	string[] resultStrings = itemString.Split('.');

	// If the string contains more than one period, increase the 
	// height by ten pixels; otherwise, increase the height by 
	// five pixels.
	if (resultStrings.Length>2)
	{
		e.ItemHeight += 10;
	}
	else
	{
		e.ItemHeight += 5;
	}

}

Friend WithEvents ListBox1 As System.Windows.Forms.ListBox

Private Sub InitializeOwnerDrawnListBox()
    Me.ListBox1 = New System.Windows.Forms.ListBox

    ' Set the location and size.
    ListBox1.Location = New Point(20, 20)
    ListBox1.Size = New Size(240, 240)

    ' Populate the ListBox.ObjectCollection property 
    ' with several strings, using the AddRange method.
    Me.ListBox1.Items.AddRange(New Object() _
        {"System.Windows.Forms", "System.Drawing", "System.Xml", _
        "System.Net", "System.Runtime.Remoting", "System.Web"})

    ' Turn off the scrollbar.
    ListBox1.ScrollAlwaysVisible = False

    ' Set the border style to a single, flat border.
    ListBox1.BorderStyle = BorderStyle.FixedSingle

    ' Set the DrawMode property to the OwnerDrawVariable value. 
    ' This means the MeasureItem and DrawItem events must be 
    ' handled.
    ListBox1.DrawMode = DrawMode.OwnerDrawVariable
    Me.Controls.Add(Me.ListBox1)
End Sub


' Handle the DrawItem event for an owner-drawn ListBox.
Private Sub ListBox1_DrawItem(ByVal sender As Object, _
    ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem

    ' If the item is the selected item, then draw the rectangle filled in
    ' blue. The item is selected when a bitwise And of the State property
    ' and the DrawItemState.Selected property is true. 
    If (e.State And DrawItemState.Selected = DrawItemState.Selected) Then
        e.Graphics.FillRectangle(Brushes.CornflowerBlue, e.Bounds)
    Else
        ' Otherwise, draw the rectangle filled in beige.
        e.Graphics.FillRectangle(Brushes.Beige, e.Bounds)
    End If

    ' Draw a rectangle in blue around each item.
    e.Graphics.DrawRectangle(Pens.Blue, e.Bounds)

    ' Draw the text in the item.
    e.Graphics.DrawString(Me.ListBox1.Items(e.Index), Me.Font, _
        Brushes.Black, e.Bounds.X, e.Bounds.Y)

    ' Draw the focus rectangle around the selected item.
    e.DrawFocusRectangle()
End Sub

' Handle the MeasureItem event for an owner-drawn ListBox.
Private Sub ListBox1_MeasureItem(ByVal sender As Object, _
    ByVal e As MeasureItemEventArgs) Handles ListBox1.MeasureItem

    ' Cast the sender object back to ListBox type.
    Dim theListBox As ListBox = CType(sender, ListBox)

    ' Get the string contained in each item.
    Dim itemString As String = CType(theListBox.Items(e.Index), String)

    ' Split the string at the " . "  character.
    Dim resultStrings() As String = itemString.Split(".")

    ' If the string contains more than one period, increase the 
    ' height by ten pixels; otherwise, increase the height by 
    ' five pixels.
    If (resultStrings.Length > 2) Then
        e.ItemHeight += 10
    Else
        e.ItemHeight += 5
    End If

End Sub

Comentarios

La ListBox.ObjectCollection clase almacena los elementos mostrados en ListBoxel.The ListBox.ObjectCollection class stores the items displayed in the ListBox. Hay otras dos colecciones definidas dentro de la ListBox clase que permiten determinar qué elementos se seleccionan en esta colección.There are two other collections defined within the ListBox class that enable you to determine what items are selected within this collection. La ListBox.SelectedObjectCollection clase proporciona propiedades y métodos para determinar qué elementos se seleccionan ListBox.ObjectCollectionen, mientras que ListBox.SelectedIndexCollection la clase permite determinar qué índices de ListBox.ObjectCollection están seleccionados.The ListBox.SelectedObjectCollection class provides properties and methods for determining what items are selected within the ListBox.ObjectCollection, while the ListBox.SelectedIndexCollection class enables you to determine what indexes within the ListBox.ObjectCollection are selected.

Hay varias maneras de agregar elementos a la colección.There are a number of ways to add items to the collection. El Add método proporciona la capacidad de agregar un solo objeto a la colección.The Add method provides the ability to add a single object to the collection. Para agregar un número de objetos a la colección, cree una matriz de elementos y asígnela al AddRange método.To add a number of objects to the collection, you create an array of items and assign it to the AddRange method. Si desea insertar un objeto en una ubicación concreta de la colección, puede utilizar el Insert método.If you want to insert an object at a specific location within the collection, you can use the Insert method. Para quitar elementos, puede utilizar el Remove método o el RemoveAt método si sabe dónde se encuentra el elemento dentro de la colección.To remove items, you can use either the Remove method or the RemoveAt method if you know where the item is located within the collection. El Clear método permite quitar todos los elementos de la colección en lugar de utilizar el Remove método para quitar un solo elemento cada vez.The Clear method enables you to remove all items from the collection instead of using the Remove method to remove a single item at a time.

También puede manipular los elementos de un ListBox mediante la DataSource propiedad.You can also manipulate the items of a ListBox by using the DataSource property. DataSource Si usa la propiedad para agregar elementos a un ListBox ListBox, puede ver los elementos de mediante la Items propiedad, pero no puede agregar ListBox.ObjectCollectiono quitar elementos de la lista mediante los métodos de.If you use the DataSource property to add items to a ListBox, you can view the items in the ListBox using the Items property but you cannot add or remove items from the list using the methods of the ListBox.ObjectCollection.

Además de los métodos y las propiedades para agregar y quitar elementos, ListBox.ObjectCollection también proporciona métodos para buscar elementos dentro de la colección.In addition to methods and properties for adding and removing items, the ListBox.ObjectCollection also provides methods to find items within the collection. El Contains método le permite determinar si un objeto es un miembro de la colección.The Contains method enables you to determine whether an object is a member of the collection. Una vez que sepa que el elemento se encuentra en la colección, puede utilizar el IndexOf método para determinar dónde se encuentra el elemento dentro de la colección.Once you know that the item is located within the collection, you can use the IndexOf method to determine where the item is located within the collection.

Constructores

ListBox.ObjectCollection(ListBox) ListBox.ObjectCollection(ListBox) ListBox.ObjectCollection(ListBox) ListBox.ObjectCollection(ListBox)

Inicializa una nueva instancia de la clase ListBox.ObjectCollection.Initializes a new instance of ListBox.ObjectCollection.

ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection) ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection) ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection) ListBox.ObjectCollection(ListBox, ListBox+ObjectCollection)

Inicializa una nueva instancia de ListBox.ObjectCollection basada en otra colección ListBox.ObjectCollection.Initializes a new instance of ListBox.ObjectCollection based on another ListBox.ObjectCollection.

ListBox.ObjectCollection(ListBox, Object[]) ListBox.ObjectCollection(ListBox, Object[]) ListBox.ObjectCollection(ListBox, Object[]) ListBox.ObjectCollection(ListBox, Object[])

Inicializa una nueva instancia de ListBox.ObjectCollection que contiene una matriz de objetos.Initializes a new instance of ListBox.ObjectCollection containing an array of objects.

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 o establece el elemento en el índice especificado de la colección.Gets or sets the item at the specified index within the collection.

Métodos

Add(Object) Add(Object) Add(Object) Add(Object)

Agrega un elemento a la lista de elementos de un control ListBox.Adds an item to the list of items for a ListBox.

AddRange(ListBox+ObjectCollection) AddRange(ListBox+ObjectCollection) AddRange(ListBox+ObjectCollection) AddRange(ListBox+ObjectCollection)

Agrega los elementos de una clase ListBox.ObjectCollection existente a la lista de elementos de un control ListBox.Adds the items of an existing ListBox.ObjectCollection to the list of items in a ListBox.

AddRange(Object[]) AddRange(Object[]) AddRange(Object[]) AddRange(Object[])

Agrega una matriz de elementos a la lista de elementos de ListBox.Adds an array of items to the list of items for a ListBox.

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

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

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

Determina si el elemento especificado está ubicado en la colección.Determines whether the specified item is located within the collection.

CopyTo(Object[], Int32) CopyTo(Object[], Int32) CopyTo(Object[], Int32) CopyTo(Object[], Int32)

Copia toda la colección en una matriz de objetos existente en el lugar especificado de la matriz.Copies the entire collection into an existing array of objects 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 va a utilizar para recorrer en iteración la colección de elementos.Returns an enumerator to use to iterate through the 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(Object) IndexOf(Object) IndexOf(Object) IndexOf(Object)

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

Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object) Insert(Int32, Object)

Inserta un elemento en el cuadro de lista en el índice especificado.Inserts an item into the list box at the specified index.

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

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

(Inherited from Object)
Remove(Object) Remove(Object) Remove(Object) Remove(Object)

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

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

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

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.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

Copia los elementos de la colección en una matriz a partir de un índice de matriz concreto.Copies the elements of the collection to an array, starting at a particular array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

Para obtener una descripción de este miembro, vea IsSynchronized.For a description of this member, see IsSynchronized.

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

Para una descripción de este miembro, vea SyncRoot.For a description of this member, see SyncRoot.

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

Agrega un objeto a la clase ListBox.Adds an object to the ListBox class.

IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize

Para una descripción de este miembro, vea IsFixedSize.For a description of this member, see IsFixedSize.

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

Consulte también: