ListBox (Clase)
Actualización: noviembre 2007
Representa un control de Windows para mostrar una lista de elementos.
Ensamblado: System.Windows.Forms (en System.Windows.Forms.dll)
[DefaultBindingPropertyAttribute("SelectedValue")] [ComVisibleAttribute(true)] [ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] public class ListBox : ListControl
/** @attribute DefaultBindingPropertyAttribute("SelectedValue") */
/** @attribute ComVisibleAttribute(true) */
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */
public class ListBox extends ListControl
El control ListBox permite mostrar una lista de elementos para que el usuario los seleccione haciendo clic en ellos. Un control ListBox puede proporcionar una o varias selecciones mediante la propiedad SelectionMode. ListBox también proporciona la propiedad MultiColumn para poder mostrar los elementos en columnas en lugar de mostrarlos en una lista vertical. Con esto, el control puede mostrar más elementos visibles y el usuario ya no necesita desplazarse a un elemento.
Normalmente, Windows controla la tarea de dibujar los elementos que se van a mostrar en el control ListBox. Utilice la propiedad DrawMode y controle los eventos MeasureItem y DrawItem de manera que pueda reemplazar el dibujo automático de Windows y dibujar los elementos. Utilice controles ListBox dibujados por el propietario para mostrar elementos de alto variable, imágenes, un color o una fuente diferente para el texto de cada elemento de la lista. La propiedad HorizontalExtent, GetItemHeight y GetItemRectangle también le ayudan a dibujar sus propios elementos.
Además de la funcionalidad de presentación y selección, ListBox también proporciona funciones que permiten agregar de manera eficaz elementos al control ListBox y buscar texto en los elementos de la lista. Los métodos BeginUpdate y EndUpdate permiten agregar un gran número de elementos al ListBox sin que el control se tenga que volver a dibujar cada vez que se agrega un elemento a la lista. Los métodos FindString y FindStringExact permiten buscar un elemento de la lista que contenga una cadena de búsqueda específica.
Las propiedades Items, SelectedItems y SelectedIndices proporcionan acceso a las tres colecciones que ListBox utiliza. En la tabla siguiente se presentan las tres colecciones que ListBox utiliza y se indica su uso dentro del control.
|
Clase de colección |
Para utilizarla en el ListBox |
|---|---|
|
Contiene todos los elementos incluidos en el control ListBox. |
|
|
Contiene una colección de los elementos seleccionados, que constituye un subconjunto de los elementos incluidos en el control ListBox. |
|
|
Contiene una colección de los índices seleccionados, que constituye un subconjunto de los índices de ListBox.ObjectCollection. Estos índices especifican los elementos seleccionados. |
En los tres ejemplos siguientes se muestran las tres colecciones indizadas que admite la clase ListBox.
En la tabla siguiente, se muestra un ejemplo de cómo ListBox.ObjectCollection almacena los elementos de ListBox así como su estado de selección dentro de un control ListBox de ejemplo.
|
Índice |
Elemento |
Estado de selección dentro del control ListBox |
|---|---|---|
|
0 |
objeto1 |
No seleccionado |
|
1 |
objeto2 |
Seleccionado |
|
2 |
objeto3 |
No seleccionado |
|
3 |
objeto4 |
Seleccionado |
|
4 |
objeto5 |
Seleccionado |
En función de la clase ListBox.ObjectCollection que se muestra en la tabla anterior, en esta tabla se muestra cómo aparecerá ListBox.SelectedObjectCollection.
|
Índice |
Elemento |
|---|---|
|
0 |
objeto2 |
|
1 |
objeto4 |
|
2 |
objeto5 |
En función de la clase ListBox.ObjectCollection que se muestra en la tabla anterior, en esta tabla se muestra cómo aparecerá ListBox.SelectedIndexCollection.
|
Índice |
Índice de elemento |
|---|---|
|
0 |
1 |
|
1 |
3 |
|
2 |
4 |
El método Add de la clase ListBox.ObjectCollection permite agregar elementos a ListBox. El método Add puede aceptar cualquier objeto al agregar un miembro a ListBox. Cuando se agrega un objeto a ListBox, el control utiliza el texto definido en el método ToString del objeto, a menos que se especifique un nombre de miembro del objeto en la propiedad DisplayMember. Para agregar elementos, además del método Add de la clase ListBox.ObjectCollection, puede usar también la propiedad DataSource de la clase ListControl.
Nota:
|
|---|
|
Si tiene un ListBox, ComboBox o CheckedListBox en un formulario de Windows de base y desea modificar las colecciones de cadenas de esos controles en un formulario de Windows derivado, las colecciones de cadenas de estos controles del formulario de Windows de base deben estar vacías. Si las colecciones de cadenas no están vacías, se establecen como de sólo lectura cuando se deriva otro formulario de Windows. |
En el siguiente ejemplo de código se muestra cómo crear un control ListBox que muestre varios elementos en columnas y pueda tener seleccionado más de un elemento en la lista del control. El código del ejemplo agrega 50 elementos a ListBox mediante el método Add de la clase ListBox.ObjectCollection y, a continuación, selecciona tres elementos de la lista mediante el método SetSelected. A continuación, el código muestra valores de la colección ListBox.SelectedObjectCollection, mediante la propiedad SelectedItems, y de ListBox.SelectedIndexCollection, mediante la propiedad SelectedIndices. En este ejemplo se supone que el código está ubicado en Form y que se lo llama desde dicho formulario.
private void button1_Click(object sender, System.EventArgs e) { // Create an instance of the ListBox. ListBox listBox1 = new ListBox(); // Set the size and location of the ListBox. listBox1.Size = new System.Drawing.Size(200, 100); listBox1.Location = new System.Drawing.Point(10,10); // Add the ListBox to the form. this.Controls.Add(listBox1); // Set the ListBox to display items in multiple columns. listBox1.MultiColumn = true; // Set the selection mode to multiple and extended. listBox1.SelectionMode = SelectionMode.MultiExtended; // Shutdown the painting of the ListBox as items are added. listBox1.BeginUpdate(); // Loop through and add 50 items to the ListBox. for (int x = 1; x <= 50; x++) { listBox1.Items.Add("Item " + x.ToString()); } // Allow the ListBox to repaint and display the new items. listBox1.EndUpdate(); // Select three items from the ListBox. listBox1.SetSelected(1, true); listBox1.SetSelected(3, true); listBox1.SetSelected(5, true); // Display the second selected item in the ListBox to the console. System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString()); // Display the index of the first selected item in the ListBox. System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString()); }
private void button1_Click(Object sender, System.EventArgs e)
{
// Create an instance of the ListBox.
ListBox listBox1 = new ListBox();
// Set the size and location of the ListBox.
listBox1.set_Size(new System.Drawing.Size(200,100));
listBox1.set_Location(new System.Drawing.Point(10,10));
// Add the ListBox to the form.
this.get_Controls().Add(listBox1);
// Set the ListBox to display items in multiple columns.
listBox1.set_MultiColumn(true);
// Set the selection mode to multiple and extended.
listBox1.set_SelectionMode(SelectionMode.MultiExtended);
// Shutdown the painting of the ListBox as items are added.
listBox1.BeginUpdate();
// Loop through and add 50 items to the ListBox.
for (int x = 1; x <= 50; x++) {
listBox1.get_Items().Add(("Item" + (new Integer(x)).ToString()));
}
// Allow the ListBox to repaint and display the new items.
listBox1.EndUpdate();
// Select three items from the ListBox.
listBox1.SetSelected(1,true);
listBox1.SetSelected(3,true);
listBox1.SetSelected(5,true);
// Display the second selected item in the ListBox to the console.
System.Diagnostics.Debug.WriteLine
(listBox1.get_SelectedItems().get_Item(1).ToString());
// Display the index of the first selected item in the ListBox.
System.Diagnostics.Debug.WriteLine((new Integer
(listBox1.get_SelectedIndices().get_Item(0))).ToString());
} //button1_Click
private function button1_Click(sender : Object, e : System.EventArgs) { // Create an instance of the ListBox. var listBox1 : ListBox = new ListBox(); // Set the size and location of the ListBox. listBox1.Size = new System.Drawing.Size(200, 100); listBox1.Location = new System.Drawing.Point(10,10); // Add the ListBox to the form. this.Controls.Add(listBox1); // Set the ListBox to display items in multiple columns. listBox1.MultiColumn = true; // Set the selection mode to multiple and extended. listBox1.SelectionMode = SelectionMode.MultiExtended; // Shutdown the painting of the ListBox as items are added. listBox1.BeginUpdate(); // Loop through and add 50 items to the ListBox. for (var x : int = 1; x <= 50; x++) { listBox1.Items.Add("Item " + x.ToString()); } // Allow the ListBox to repaint and display the new items. listBox1.EndUpdate(); // Select three items from the ListBox. listBox1.SetSelected(1, true); listBox1.SetSelected(3, true); listBox1.SetSelected(5, true); @if(@DEBUG) // Display the second selected item in the ListBox to the console. System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString()); // Display the index of the first selected item in the ListBox. System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString()); @end }
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.ListControl
System.Windows.Forms.ListBox
Microsoft.VisualBasic.Compatibility.VB6.DirListBox
Microsoft.VisualBasic.Compatibility.VB6.FileListBox
System.Windows.Forms.CheckedListBox
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Pocket PC
.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Nota: