如果我有一个带有未知数量标签的面板,我如何浏览所有标签并更改其中的 .text 值?我试过这样的事情:
for each x as label in mypanel
x.text = "whatever"
next
但我收到一个错误,即 mypanel 不是集合。
标签是 mypanel 的子标签。
如果我有一个带有未知数量标签的面板,我如何浏览所有标签并更改其中的 .text 值?我试过这样的事情:
for each x as label in mypanel
x.text = "whatever"
next
但我收到一个错误,即 mypanel 不是集合。
标签是 mypanel 的子标签。
对于获胜形式,请尝试:
for each x as Control in mypanel.Controls
if TypeOf x Is Label Then
CType(x, Label).text = "whatever"
end if
next
For Each lbl As Label in myPanel.Controls
lbl.Text = "whatever"
Next
这是假设 myPanel 上的所有内容都是标签。如果还有其他控件,则必须测试它们是否为标签:
For Each ctl as Control in myPanel.Controls
If Ctl.GetType = Label.GetType Then
CType(ctl, Label).text = "whatever"
End if
Next
循环遍历面板中的所有控件,然后确定每个控件是否为Label
,如下所示:
For Each theControl As Control In myPanel.Controls
If TypeOf theControl Is Label Then
' Change the text here
TryCast(theControl, Label).Text = "whatever"
End If
Next
更新:
要考虑面板中的子控件,请执行以下操作:
Dim listOfLabels As New List(Of Control)
Public Sub GetAllLabelsIn(container As Control)
For Each theControl As Control In container.Controls
If TypeOf theControl Is Label Then
listOfLabels.Add(theControl)
If theControl.Controls.Count > 0 Then
GetAllLabelsIn(theControl)
End If
End If
Next
End Sub
现在你可以这样称呼它:
listOfLabels = new List(Of Control)
GetAllLabelsIn(myPanel)
For Each theControl As Control In listOfLabels
If TypeOf theControl Is Label Then
' Change the text here
TryCast(theControl, Label).Text = "whatever"
End If
Next
您首先只能选择Label
s。这也返回容器内容器内的标签等......
' Inside a module
<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
Dim result As New ArrayList()
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is T Then result.Add(ctrl)
result.AddRange(ChildControls(Of T)(ctrl))
Next
Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function
用法:
For Each myLabel as Label in myPanel.ChildControls(Of Label)
myLabel.Text = "I'm a label!"
Next