índice de vb.net

Prueba de acceso a listas: de un ListBox, Array y Collection (compatible con versiones anteriores de Visual Basic)


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
'
' ©Guillermo 'guille' Som, 2000
'
' Para compilar:
' vbc WFLB_20Oct.vb /r:System.dll /r:system.winforms.dll /r:System.Drawing.dll
'------------------------------------------------------------------------------
Imports System
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms

Namespace Guille.Ejemplos.WFLB_20OctNamespace

    Public Class WFLB_20Oct
        Inherits System.WinForms.Form

        'Required by the Win Forms Designer
        Private components As System.ComponentModel.Container
        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 Microsoft.VisualBasic.Compatibility.VB6.Collection
        Private m_Col As Microsoft.VisualBasic.Compatibility.VB6.Collection

        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_20Oct())
        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.TextBox1 = New System.WinForms.TextBox
            Me.ListBox1 = New System.WinForms.ListBox
            Me.TextBox2 = New System.WinForms.TextBox
            Me.LabelStatus = New System.WinForms.Label
            Me.ButtonCrearLista = New System.WinForms.Button
            Me.RadioButton1 = New System.WinForms.RadioButton
            Me.Label1 = New System.WinForms.Label
            Me.ButtonSalir = New System.WinForms.Button
            Me.ButtonForI = New System.WinForms.Button
            Me.Button2Array = New System.WinForms.Button
            Me.ButtonForEach = New System.WinForms.Button
            Me.RadioButton3 = New System.WinForms.RadioButton
            Me.RadioButton2 = New System.WinForms.RadioButton
            Me.ButtonAdd = New System.WinForms.Button
            Me.Button2Collection = New System.WinForms.Button

            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)
            'TextBox1.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))

            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 = 7
            TextBox2.Size = New System.Drawing.Size(244, 132)
            'TextBox2.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent))

            LabelStatus.Location = New System.Drawing.Point(0, 347)
            LabelStatus.Text = "©Guillermo 'guille' Som, 2000"
            LabelStatus.Size = New System.Drawing.Size(390, 16)
            LabelStatus.BorderStyle = System.WinForms.BorderStyle.Fixed3D
            LabelStatus.Dock = System.WinForms.DockStyle.Bottom
            LabelStatus.TabIndex = 14

            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(390, 363)
            '@design Me.GridSize = New System.Drawing.Size(4, 4)
            Me.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))

            RadioButton1.Location = New System.Drawing.Point(264, 172)
            RadioButton1.Size = New System.Drawing.Size(116, 16)
            RadioButton1.TabIndex = 8
            RadioButton1.TabStop = True
            RadioButton1.Text = "Usar ListBox"
            RadioButton1.Checked = True
            RadioButton1.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent))

            Label1.Location = New System.Drawing.Point(12, 12)
            Label1.Text = "Palabra:"
            Label1.Size = New System.Drawing.Size(48, 16)
            Label1.TabIndex = 0
            'Label1.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent))

            ButtonSalir.Location = New System.Drawing.Point(304, 316)
            ButtonSalir.Size = New System.Drawing.Size(75, 23)
            ButtonSalir.TabIndex = 13
            ButtonSalir.Text = "Salir"
            ButtonSalir.AddOnClick(New System.EventHandler(AddressOf Me.ButtonSalir_Click))
            ButtonSalir.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 = 11
            ButtonForI.Text = "For i =..."
            ButtonForI.AddOnClick(New System.EventHandler(AddressOf Me.ButtonForI_Click))
            ButtonForI.AddOnMouseMove(New System.WinForms.MouseEventHandler(AddressOf Me.MouseMoveEvent))

            Button2Array.Location = New System.Drawing.Point(264, 84)
            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))

            ButtonForEach.Location = New System.Drawing.Point(264, 272)
            ButtonForEach.Size = New System.Drawing.Size(75, 23)
            ButtonForEach.TabIndex = 12
            ButtonForEach.Text = "For Each..."
            ButtonForEach.AddOnClick(New System.EventHandler(AddressOf Me.ButtonForEach_Click))
            ButtonForEach.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 = 10
            RadioButton3.Text = "Usar Collection"
            RadioButton3.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 = 9
            RadioButton2.Text = "Usar Array"
            RadioButton2.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))

            Button2Collection.Location = New System.Drawing.Point(264, 116)
            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))

            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
                ' Ya no se usa Set para asignar un objeto a una variable
                m_Col = New Microsoft.VisualBasic.Compatibility.VB6.Collection
                ' Añadir cada uno de los elementos del ListBox a la colección
                For i = 0 To .Items.Count-1
                    m_Col.Add("Collection_" & .GetItemText(.Items(i)))
                Next
            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
            'LabelStatus.Text = " " & msg
            'Exit Sub
            ' Pero creo que es más "sobrecargado" que usando TypeName
            '
            ' 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
            '
            ' 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_20Oct"
            '   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
            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
                s = s & "con el contenido de la Colección" & 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
                    For Each t in m_Col
                        i += 1
                        s = s & t & " (" & i.ToString & ")" & vbCrLf
                    Next
                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
                s &= "con el contenido de la Colección" & vbCrLf
                ' En las colecciones, se supone que son objetos
                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
                    For i = 1 To m_Col.Count
                        s = s & m_Col(i).ToString & " (" & i.ToString & ")" & vbCrLf
                    Next
                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


Ir al índice de vb.net

la Luna del Guille o... el Guille que está en la Luna... tanto monta...