问题描述
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)
因此,我创建了一个创建列表框的按钮,并在创建时为每个列表框设置了一个名称。 此列表框充满了我选择的文件,但是如何从指定的列表框中获取值。
For Each nome In ListBox1.Items
...
如果无法在主代码上调用ListBox1,因为尚未创建。
那我该怎么办?我如何才能获得创建的最后一个列表框的正确列表框。
解决方法
您的问题是,编译器在编译时无法了解ListBoxi。直到运行时才创建它。
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