为什么Me.Controls()中缺少控件

BKS*_*ell 1 vb.net visual-studio

大家好.我肯定错过了什么.我试图循环浏览表格上的标签,但看起来我错过了很多标签......我的表格总共有69个标签,我只能在msgbox上获得5个点击.所有控件都放在表单上的设计时间而不是面板或标签上.在检查me.controls时.计数不正确,因为它缺少64个控件.(遗失的标签).

Dim ctl As Control
For Each ctl In Me.Controls
  If TypeOf ctl Is Label Then
    MsgBox(ctl.Name)
  End If
Next ctl
Run Code Online (Sandbox Code Playgroud)

任何想法为什么他们不会出现?

布拉德斯文德尔

Jos*_*osh 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
Run Code Online (Sandbox Code Playgroud)