Search code examples
vb.netvariablesbuttonlistboxcall

How to get a "item" if I created it on the code


    Public WithEvents newListBox As Windows.Forms.ListBox
        newListBox = New Windows.Forms.ListBox
    newListBox.Name = "ListBox" & i
    newListBox.Height = 44
    newListBox.Width = 250
    newListBox.Top = 10 + i * 50
    newListBox.Left = 150
    newListBox.Tag = i
    Me.Controls.Add(newListBox)

So I created a button that create a listbox and I set a name for each listbox while created. This listbox are filled with files that I select, but how can I get the values from a especified listbox like.

For Each nome In ListBox1.Items

...

If I cant call ListBox1 on the main code cuz its not created yet.

So what should I do ? How can I get the right listbox insted of the last one created.


Solution

  • Your problem is that the compiler can't know about ListBoxi at compile time. It is not created until runtime.

    Friend WithEvents newListBox As ListBox
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Static i As Integer = 1
        newListBox = New ListBox
        newListBox.Name = "ListBox" & i
        newListBox.Height = 44
        newListBox.Width = 250
        newListBox.Top = 10 + i * 50
        newListBox.Left = 150
        newListBox.Tag = i
        Me.Controls.Add(newListBox)
        i += 1
    End Sub
    
    
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim listBoxi = TryCast(Controls.Find("ListBox1", True).FirstOrDefault(), ListBox)
        For Each item In listBoxi.Items
    
        Next
    End Sub