首页 > 解决方案 > 如果我在代码上创建了“项目”,如何获得它

问题描述

    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,因为它尚未创建。

所以我该怎么做 ?我怎样才能获得最后一个创建的正确列表框。

标签: vb.netvariablesbuttonlistboxcall

解决方案


您的问题是编译器在编译时无法了解 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

推荐阅读