Dim ctl As Control
For Each ctl In Me.Controls
If TypeOf ctl Is Label Then
MsgBox(ctl.Name)
End If
Next ctl
为什么他们不会出现的任何想法?
Brad Swindell
答案 0 :(得分:5)
Controls集合是一个层次结构。你只是获得顶级控制。如果你想获得所有控件,那么你需要递归地挖掘每个子控件Control集合。
所有控件都放在设计上 在表格上的时间,而不是面板或 标签。
请记住,GroupBox
也是一个控件,它也有自己的Controls属性。
这个函数应该可以提供你想要的东西,但是我的VB.Net非常非常生疏,所以如果它不编译我道歉。
Private Sub PrintAllControlsRecursive(col As Control.ControlCollection, ctrlType As Type)
If col Is Nothing OrElse col.Count = 0 Then
Return
End If
For Each c As Control In col
If c.GetType() = ctrlType Then
MessageBox.Show(c.Name)
End If
If c.HasChildren Then
PrintAllControlsRecursive(c.Controls, ctrlType)
End If
Next
End Sub
答案 1 :(得分:0)
Sub PrintAllControls(ByVal ParentCtl As Control)
Dim ctl As Control
MsgBox(ParentCtl.Name + " start", MsgBoxStyle.Exclamation)
For Each ctl In ParentCtl.Controls
MsgBox(ctl.Name)
If ctl.HasChildren = True Then
PrintAllControls(ctl)
End If
Next
MsgBox(ParentCtl.Name + " End", MsgBoxStyle.Information)
End Sub
答案 2 :(得分:0)
只需使用LINQ和带selectmany的递归lambda来展平层次结构:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim act As Func(Of Control, IEnumerable(Of Control)) =
Function(ctl) ctl.Controls.Cast(Of Control)().SelectMany(
Function(ctl2) ctl2.Controls.Cast(Of Control)().
Union(act(ctl2))).Union(ctl.Controls.Cast(Of Control))
MsgBox(Join((From c In act(Me).Distinct Order By c.Name
Select c.Name & "--" & c.GetType.ToString).ToArray, vbCrLf))
End Sub
根本不是稗子编程,也不是重复项目或模糊错误的机会......
答案 3 :(得分:-1)
请确保您在表单完全收费后找到控件,否则如果您尝试在加载过程中列出控件,则me.controls.count将为零。