2010-11-18 181 views
1

嘿傢伙。我肯定錯過了什麼。我試圖循環表格中的標籤,但看起來我缺少了很多標籤......我的表格上共有69個標籤,我只在msgbox上獲得5個標籤。所有控件都放在窗體上的設計時間上,而不是在面板或選項卡上。還要檢查me.controls。計數不正確,因爲它完全缺少64個控件。 (缺失的標籤)。爲什麼控件從Me.Controls()中丟失()

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

任何想法,爲什麼他們不會出現?

布拉德斯溫德爾

回答

4

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 
+0

Quote:「不在面板或標籤」。也許。 – 2010-11-18 19:59:26

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 
0

拼合。

只需使用LINQ和遞歸拉姆達與向的SelectMany扁平化層級:

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 

不稗節目在所有重複,也不項目或不明顯的錯誤的機會......

-1

確保你」在表單完全充電後重新找到控件,否則如果在加載過程中嘗試列出控件,則me.controls.count將爲零。