集合属性引用的控件Controls
可以通过其名称访问,如下所示:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
For i As Integer = 1 to ds.Tables("MyTable").Rows.Count
Dim panel As Panel = CType(MyForm.Controls("MyPanel" & i.ToString()), Panel)
Dim label As Label = CType(panel.Controls("MyLabel" & i.ToString()), Label)
Next
End Sub
但是,您可能会发现在创建它们时将它们全部添加到列表中更容易,以便以后可以访问它们。例如,如果您像这样创建了几个列表作为表单上的私有字段:
Private myPanels As New List(Of Panel)()
Private myLabels As New List(Of Label)()
然后,当您创建控件时,您可以将它们添加到列表中,如下所示:
For i = 1 To ds.Tables("MyTable").Rows.Count
Dim nextPanel As New Panel()
Dim nextLabel As New Label()
nextPanel.Controls.Add(nextLabel)
MyForm.Controls.Add(nextPanel)
nextLabel.Name = "MyLabel" & i.ToString()
nextPanel.Name = "MyPanel" & i.ToString()
'Add them to the lists
myPanels.Add(nextPanel)
myLabels.Add(nextLabel)
Next
然后,当您需要遍历它们时,它会容易得多,并且您不必关心创建的总数:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
For Each label As Label In myLabels
' ...
Next
End Sub
然而,值得一提的是,如果您将标签添加到FlowLayoutPanel控件而不是直接在表单上的单独面板中,那么您所做的事情可能会大大简化。