Actualizado: 25/Oct/2000
Por ahora sólo está el código, más adelante puede que comente el código mostrado...
En otra ocasión inertaré unas "capturas" del formulario... talvez te hagas una mejor idea de cómo funciona...'------------------------------------------------------------------------------ ' Prueba de acceso a los elementos de un ListBox (20/Oct/00) ' También se prueban los Arrays y Colecciones ' Prueba con ArrayList (de System.Collections) (22/Oct/00) ' También con StringCollection ' ' ©Guillermo 'guille' Som, 2000 ' ' Para compilar: ' vbc WFLB_22Oct.vb /r:System.dll /r:system.winforms.dll /r:System.Drawing.dll '------------------------------------------------------------------------------ Imports System Imports System.ComponentModel Imports System.Drawing Imports System.WinForms ' Imports System.Collections ' Namespace Guille.Ejemplos.WFLB_22OctNamespace Public Class WFLB_22Oct Inherits System.WinForms.Form 'Required by the Win Forms Designer Private components As System.ComponentModel.Container Private chkStringCollection As System.WinForms.CheckBox Private RadioButton3 As System.WinForms.RadioButton Private RadioButton2 As System.WinForms.RadioButton Private RadioButton1 As System.WinForms.RadioButton Private Button2Collection As System.WinForms.Button Private LabelStatus As System.WinForms.Label Private Button2Array As System.WinForms.Button Private ButtonCrearLista As System.WinForms.Button Private ButtonForEach As System.WinForms.Button Private ButtonSalir As System.WinForms.Button Private ButtonForI As System.WinForms.Button Private TextBox2 As System.WinForms.TextBox Private ListBox1 As System.WinForms.ListBox Private ButtonAdd As System.WinForms.Button Private TextBox1 As System.WinForms.TextBox Private Label1 As System.WinForms.Label ' Constantes Private Const vbCr As Char = CChar(13) Private Const vbLf As Char = CChar(10) Private Const vbCrLf As String = vbCr & vbLf Private Const vbTab As Char = CCHar(9) ' ' Array y colección a usar en el programa Private m_Array() As String Private m_Col As New ArrayList Private m_StrCol As New StringCollection ' Public Sub New() MyBase.New 'This call is required by the Win Forms Designer. InitializeComponent ' TODO: Add any constructor code after InitializeComponent call End Sub 'Clean up any resources being used Overrides Public Sub Dispose() MyBase.Dispose components.Dispose End Sub 'The main entry point for the application Shared Sub Main() System.WinForms.Application.Run(New WFLB_22Oct()) End Sub 'NOTE: The following procedure is required by the Win Forms Designer 'Do not modify it. Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container Me.Button2Collection = New System.WinForms.Button Me.ButtonForI = New System.WinForms.Button Me.ButtonAdd = New System.WinForms.Button Me.RadioButton2 = New System.WinForms.RadioButton Me.ListBox1 = New System.WinForms.ListBox Me.RadioButton1 = New System.WinForms.RadioButton Me.RadioButton3 = New System.WinForms.RadioButton Me.ButtonSalir = New System.WinForms.Button Me.ButtonCrearLista = New System.WinForms.Button Me.TextBox2 = New System.WinForms.TextBox Me.LabelStatus = New System.WinForms.Label Me.ButtonForEach = New System.WinForms.Button Me.TextBox1 = New System.WinForms.TextBox Me.Label1 = New System.WinForms.Label Me.Button2Array = New System.WinForms.Button Me.chkStringCollection = New System.WinForms.CheckBox Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.Text = "Prueba de Listas" Me.CancelButton = ButtonSalir '@design Me.TrayLargeIcon = True Me.BorderStyle = System.WinForms.FormBorderStyle.FixedSingle Me.AcceptButton = ButtonAdd '@design Me.TrayHeight = 0 Me.ClientSize = New System.Drawing.Size(402, 363) '@design Me.GridSize = New System.Drawing.Size(4, 4) Me.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) Button2Collection.Location = New System.Drawing.Point(264, 108) Button2Collection.Size = New System.Drawing.Size(112, 23) Button2Collection.TabIndex = 6 Button2Collection.Text = "Pasar a Collection" Button2Collection.AddOnClick(New System.EventHandler(AddressOf Me.Button2Collection_Click)) Button2Collection.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) ButtonForI.Location = New System.Drawing.Point(264, 244) ButtonForI.Size = New System.Drawing.Size(75, 23) ButtonForI.TabIndex = 12 ButtonForI.Text = "For i =..." ButtonForI.AddOnClick(New System.EventHandler(AddressOf Me.ButtonForI_Click)) ButtonForI.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) ButtonAdd.Location = New System.Drawing.Point(264, 8) ButtonAdd.Size = New System.Drawing.Size(75, 23) ButtonAdd.TabIndex = 2 ButtonAdd.Text = "Añadir" ButtonAdd.AddOnClick(New System.EventHandler(AddressOf Me.ButtonAdd_Click)) ButtonAdd.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) RadioButton2.Location = New System.Drawing.Point(264, 192) RadioButton2.Size = New System.Drawing.Size(116, 16) RadioButton2.TabIndex = 10 RadioButton2.Text = "Usar Array" RadioButton2.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) ListBox1.Location = New System.Drawing.Point(12, 44) ListBox1.Size = New System.Drawing.Size(244, 108) ListBox1.TabIndex = 3 ListBox1.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) RadioButton1.Location = New System.Drawing.Point(264, 172) RadioButton1.Size = New System.Drawing.Size(116, 16) RadioButton1.TabIndex = 9 RadioButton1.TabStop = True RadioButton1.Text = "Usar ListBox" RadioButton1.Checked = True RadioButton1.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) RadioButton3.Location = New System.Drawing.Point(264, 212) RadioButton3.Size = New System.Drawing.Size(116, 16) RadioButton3.TabIndex = 11 RadioButton3.Text = "Usar Collection" RadioButton3.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) ButtonSalir.Location = New System.Drawing.Point(320, 316) ButtonSalir.Size = New System.Drawing.Size(75, 23) ButtonSalir.TabIndex = 14 ButtonSalir.Text = "Salir" ButtonSalir.AddOnClick(New System.EventHandler(AddressOf Me.ButtonSalir_Click)) ButtonSalir.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) ButtonCrearLista.Location = New System.Drawing.Point(264, 44) ButtonCrearLista.Size = New System.Drawing.Size(112, 24) ButtonCrearLista.TabIndex = 4 ButtonCrearLista.Text = "Generar lista" ButtonCrearLista.AddOnClick(New System.EventHandler(AddressOf Me.ButtonCrearLista_Click)) ButtonCrearLista.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) TextBox2.Location = New System.Drawing.Point(12, 168) TextBox2.Text = "TextBox2" TextBox2.Multiline = True TextBox2.AcceptsReturn = True TextBox2.AutoSize = False TextBox2.ScrollBars = System.WinForms.ScrollBars.Vertical TextBox2.TabIndex = 8 TextBox2.Size = New System.Drawing.Size(244, 132) LabelStatus.Location = New System.Drawing.Point(0, 347) LabelStatus.Text = "©Guillermo 'guille' Som, 2000" LabelStatus.Size = New System.Drawing.Size(402, 16) LabelStatus.BorderStyle = System.WinForms.BorderStyle.Fixed3D LabelStatus.Dock = System.WinForms.DockStyle.Bottom LabelStatus.TabIndex = 15 ButtonForEach.Location = New System.Drawing.Point(264, 272) ButtonForEach.Size = New System.Drawing.Size(75, 23) ButtonForEach.TabIndex = 13 ButtonForEach.Text = "For Each..." ButtonForEach.AddOnClick(New System.EventHandler(AddressOf Me.ButtonForEach_Click)) ButtonForEach.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) TextBox1.Location = New System.Drawing.Point(60, 8) TextBox1.Text = "TextBox1" TextBox1.AutoSize = False TextBox1.TabIndex = 1 TextBox1.Size = New System.Drawing.Size(196, 20) Label1.Location = New System.Drawing.Point(12, 12) Label1.Text = "Palabra:" Label1.Size = New System.Drawing.Size(48, 16) Label1.TabIndex = 0 Button2Array.Location = New System.Drawing.Point(264, 76) Button2Array.Size = New System.Drawing.Size(112, 23) Button2Array.TabIndex = 5 Button2Array.Text = "Pasar a Array" Button2Array.AddOnClick(New System.EventHandler(AddressOf Me.Button2Array_Click)) Button2Array.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) chkStringCollection.Location = New System.Drawing.Point(264, 136) chkStringCollection.Text = "usar StringCollection" chkStringCollection.Size = New System.Drawing.Size(128, 16) chkStringCollection.AccessibleRole = System.WinForms.AccessibleRoles.CheckButton chkStringCollection.TabIndex = 7 chkStringCollection.TextAlign = System.Drawing.ContentAlignment.MiddleLeft chkStringCollection.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent)) Me.Controls.Add(chkStringCollection) Me.Controls.Add(RadioButton3) Me.Controls.Add(RadioButton2) Me.Controls.Add(RadioButton1) Me.Controls.Add(Button2Collection) Me.Controls.Add(LabelStatus) Me.Controls.Add(Button2Array) Me.Controls.Add(ButtonCrearLista) Me.Controls.Add(ButtonForEach) Me.Controls.Add(ButtonSalir) Me.Controls.Add(ButtonForI) Me.Controls.Add(TextBox2) Me.Controls.Add(ListBox1) Me.Controls.Add(ButtonAdd) Me.Controls.Add(TextBox1) Me.Controls.Add(Label1) End Sub Protected Sub Button2Collection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Pasar el contenido del ListBox a una colección Dim i As Integer ' With ListBox1 ' Si vamos a usar un ArrayList o un StringCollection If chkStringCollection.Checked Then m_StrCol.Clear ' Añadir cada uno de los elementos del ListBox a la colección For i = 0 To .Items.Count-1 m_StrCol.Add("StringCollection_" & .GetItemText(.Items(i))) Next Else ' Las colecciones del tipo ArrayList tienen un método Clear m_Col.Clear ' Indicarle el número de elementos que vamos a necesitar ' de esta forma el array interno se ajustará una sola vez, ' ya que de no hacerlo así, cada vez que se añaden elementos ' se ajusta la capacidad del array interno. ' Aunque, de forma automática el valor de Capacity es 16, ' como se mostraría con este código: 'MessageBox.Show("Valor de Capacity: " & m_Col.Capacity.ToString) ' m_Col.Capacity = .Items.Count ' Añadir cada uno de los elementos del ListBox a la colección For i = 0 To .Items.Count-1 m_Col.Add("ArrayList (Collection)_" & .GetItemText(.Items(i))) Next ' Ajustar el número de elementos a los que realmente contiene ' ya que éstos se adaptan de forma automática. ' Después de TrimToSize, tanto Count como Capacity valen lo mismo. m_Col.TrimToSize End If ' End With End Sub Protected Sub Button2Array_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Pasar el contenido del ListBox a un Array Dim i As Integer ' With ListBox1 ' Redimensionar el Array Redim m_Array(.Items.Count) ' Asignar cada uno de los elementos del ListBox al array For i = 0 To .Items.Count - 1 m_Array(i) = "Array_" & .GetItemText(.Items(i)) Next End With End Sub Protected Sub MouseMoveEvent(ByVal sender As System.Object, ByVal e As System.WinForms.MouseEventArgs) ' Evento genérico para varios controles ' ' Mostrar un mensaje en la etiqueta de estado Dim msg As String ' ' El TypeOf no se puede usar en un Select Case, ' salvo que lo hagamos de esta forma: 'Select Case True 'Case TypeOf(sender) Is Form ' msg = "Form" 'Case TypeOf(sender) Is Button ' msg = "Button" 'End Select ' ' Lo mismo sería usar varios IFs con comparaciones 'If TypeOf(sender) Is Form Then ' msg = "©Guillermo 'guille' Som, 2000" 'ElseIf TypeOf(sender) Is Button Then ' msg = "Button" 'End If ' 'LabelStatus.Text = " " & msg 'Exit Sub ' Pero creo que es más "sobrecargado" que usando TypeName ' ' El valor por defecto msg = "©Guillermo 'guille' Som, 2000" ' ' Según el tipo de Objeto... Select Case Microsoft.VisualBasic.Information.TypeName(sender) ' Si es el formulario 'Case "WFLB_22Oct" ' msg = "©Guillermo 'guille' Som, 2000" ' Si es un botón Case "Button" Select Case CType(sender, Button).Text Case "Salir" msg = "Pulsa este botón para Salir del programa" Case "Generar lista" msg = "Añade 10 elementos de prueba a la lista" Case "For i =..." msg = "Muestra en el textbox usando un bucle For i=..." Case "For Each..." msg = "Muestra en el textbox usando un bucle For Each..." Case "Pasar a Array" msg = "Pasa el contenido del ListBox a un Array" Case "Pasar a Collection" msg = "Pasa el contenido del ListBox a una Colección" Case "Añadir" msg = "Añade la palabra al ListBox" End Select ' Si es un RadioButton Case "RadioButton" Select Case CType(sender, RadioButton).Text Case "Usar ListBox" msg = "Usa el contenido del ListBox para pasar al TextBox" Case "Usar Array" msg = "Usa el contenido del Array para pasar al TextBox" Case "Usar Collection" msg = "Usa el contenido de la colección para pasar al TextBox" End Select Case "CheckBox" Select Case CType(sender, CheckBox).Text Case "usar StringCollection" msg = "Usa colecciones del tipo StringCollection en lugar de ArrayList" End Select End Select LabelStatus.Text = " " & msg End Sub Protected Sub ButtonCrearLista_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Llenar la lista con elementos de prueba Dim i As Integer ' With ListBox1.Items .Clear For i = 0 To 10 .Add("Elemento " & i.ToString) Next End With End Sub Protected Sub ButtonForEach_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Pasar los elementos al TextBox usando For Each... Dim s As String Dim i As Integer ' s = "Usando For Each... " ' Usar diferentes listas, según el RadioButton que está seleccionado Select Case True ' Se usa el Contenido del listbox Case RadioButton1.Checked Dim t As String s = s & "con el contenido del ListBox" & vbCrLf ' Usando For Each... ' (añade más de los que hay) For Each t In ListBox1.Items i += 1 ' i=i+1 ' Salir si ya hemos recuperado todos los elementos If i>ListBox1.Items.Count Then Exit For End If ' Añadir al final un cambio de línea s = s & t & " (" & i.ToString & ")" & vbCrLf Next ' Se usa el contenido del Array Case RadioButton2.Checked ' En los arrays, para usar For Each, deben ser Objetos Dim t As Object s = s & "con el contenido del Array" & vbCrLf ' Try ' simplemente para saber si se produce error i = m_Array.Length Catch i = 0 End Try ' If i = 0 Then s = s & "No hay datos en el array" & vbCrLf & _ "Añadelos usando el botón: Pasar a Array" Else i = 0 For Each t In m_Array i += 1 s = s & t.ToString & " (" & i.ToString & ")" & vbCrLf Next End If ' Se usa el contenido de la colección Case RadioButton3.Checked Dim t As String ' ' Comprobar si usamos el StringCollection o el ArrayList If chkStringCollection.Checked Then ' s = s & "con el contenido del StringColecction" & vbCrLf Try i = m_StrCol.Count Catch i = 0 End Try If i = 0 then s = s & "No hay datos en la colección" & vbCrLf & _ "Añadelos usando el botón: Pasar a Collection" Else i = 0 For Each t in m_StrCol i += 1 s = s & t & " (" & i.ToString & ")" & vbCrLf Next End If Else s = s & "con el contenido del ArrayList" & vbCrLf Try i = m_Col.Count Catch i = 0 End Try If i = 0 then s = s & "No hay datos en la colección" & vbCrLf & _ "Añadelos usando el botón: Pasar a Collection" Else i = 0 For Each t in m_Col i += 1 s = s & t & " (" & i.ToString & ")" & vbCrLf Next End If End If End Select ' Asignarlo al textBox TextBox2.Text = s End Sub Protected Sub ButtonForI_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Pasar los elementos al TextBox usando For i =... Dim i As Integer Dim s As String ' s = "Usando For i =... " ' Usar diferentes listas, según el RadioButton que está seleccionado Select Case True ' Se usa el Contenido del listbox Case RadioButton1.Checked ' Por el sistema tradicional s &= "con el contenido del ListBox" & vbCrLf With ListBox1 For i = 0 To .Items.Count-1 ' Añadir al final un cambio de línea s = s & .GetItemText(.Items(i)) & vbCrLf Next End With ' Se usa el contenido del Array Case RadioButton2.Checked s &= "con el contenido del Array" & vbCrLf Try ' simplemente para saber si se produce error i = m_Array.Length 'Catch er As Exception ' Catch the error. 's = "Seguramente el array no contiene elementos" & vbCrLf & _ ' "Crea la lista de elementos y pulsa en Pasar a Array" & vbCrLf & _ ' vbCrLf & er.toString 'MessageBox.Show(s, "Prueba del 20/Oct/2000") 'MessageBox.Show(er.toString) ' Show friendly error message. ' Catch i = 0 End Try ' If i = 0 Then s = s & "No hay datos en el array" & vbCrLf & _ "Añadelos usando el botón: Pasar a Array" Else i = 0 For i = 0 To m_Array.Length - 1 s = s & m_Array(i) & " (" & i.ToString & ")" & vbCrLf Next End If ' Se usa el contenido de la colección Case RadioButton3.Checked ' Comprobar si usamos el StringCollection o el ArrayList If chkStringCollection.Checked Then s &= "con el contenido del StringCollection" & vbCrLf ' Comprobar que la colección esté inicializada Try i = m_StrCol.Count Catch i = 0 End Try ' If i = 0 then s = s & "No hay datos en la colección" & vbCrLf & _ "Añadelos usando el botón: Pasar a Collection" Else ' Las colecciones de Visual Basic van de 1 a .Count ' Las incluidas en System.Collections de 0 a .Count - 1 For i = 0 To m_StrCol.Count - 1 s = s & m_StrCol(i).ToString & " (" & i.ToString & ")" & vbCrLf Next End If Else s &= "con el contenido del ArrayList" & vbCrLf ' Try i = m_Col.Count Catch i = 0 End Try ' If i = 0 then s = s & "No hay datos en la colección" & vbCrLf & _ "Añadelos usando el botón: Pasar a Collection" Else ' Las colecciones de Visual Basic van de 1 a .Count ' Las incluidas en System.Collections de 0 a .Count - 1 For i = 0 To m_Col.Count - 1 s = s & m_Col(i).ToString & " (" & i.ToString & ")" & vbCrLf Next End If End If End Select ' Asignarlo al textBox TextBox2.Text = s End Sub Protected Sub ButtonSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Salir del programa Me.Close End Sub Protected Sub ButtonAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) ListBox1.Items.Add(TextBox1.Text) End Sub End Class End Namespace...
Nos vemos.
Guillermo