您还可以使用Controls.Find方法在 Forms ControlCollection 中定位您的 ComboBox
Public Class Form1
Dim maxDropDowns, y As Integer
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
maxDropDowns = 4
y = 0
Dim MyLocationX As Integer = 25
Dim MyLocationY As Integer = 25
Do While y < maxDropDowns
Dim DropDownlist As New ComboBox
DropDownlist.Name = (y + 1).ToString
DropDownlist.Location = New Point(MyLocationX, MyLocationY)
Me.Controls.Add(DropDownlist)
y = y + 1
MyLocationY = MyLocationY + 30
Loop
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim cntrls() As Control
For z = 1 To maxDropDowns
cntrls = Controls.Find(z.ToString, True)
If cntrls.Count > 0 Then
MsgBox(CType(cntrls(0), ComboBox).SelectedValue)
End If
Next
End Sub
End Class
或者您可以使用Dictionary,您有许多不同的选项,这完全取决于您想要做什么,我的偏好是创建一个控件数组,分配公共事件处理程序并从发送者对象中提取启动事件的控件。
Public Class Form1
Dim maxDropDowns, y As Integer
Dim myControls As Dictionary(Of Integer, ComboBox) = New Dictionary(Of Integer, ComboBox)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
maxDropDowns = 25
y = 0
Dim MyLocationX As Integer = 25
Dim MyLocationY As Integer = 25
Do While y < maxDropDowns
Dim DropDownlist As New ComboBox
DropDownlist.Name = (y + 1).ToString
DropDownlist.Location = New Point(MyLocationX, MyLocationY)
myControls.Add(y, DropDownlist)
Me.Controls.Add(DropDownlist)
MyLocationY = MyLocationY + 30
y = y + 1
Loop
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
For z = 0 To maxDropDowns - 1
MsgBox(myControls(z).SelectedValue)
Next
End Sub
End Class