VB.NET 不支持控件数组,与 VB6 相同。不过,你也可以做类似的事情。例如,如果您想使用相同的方法处理来自多个控件的事件,您可以这样做:
Private Sub MyClickHandler(sender As Object, e As EventArgs) Handles _
Button1.Click, _
Button2.Click, _
Button3.Click
Dim buttonThatWasClicked As Button = CType(sender, Button)
' Do something...
End Sub
如果您想创建一个可以循环的控件数组,您可以这样做,如下所示:
Dim myTextBoxes() As TextBox = New TextBox() { TextBox1, TextBox2, TextBox3 }
For i As Integer = 0 to myTextBoxes.Length - 1
myTextBoxes(i).Text = ...
Next
或者,如果您对控件的命名一致,则可以在表单的名称中找到它们Controls
收藏。例如,如果您有三个名为TextBox1
, TextBox2
, and TextBox3
,你可以像这样循环它们:
For i As Integer = 1 to 3
Dim t As TextBox = CType(Me.Controls("TextBox" & i.ToString()), TextBox)
t.Text = ...
Next