2011-12-17 83 views
0

如何通过循环遍历容器中的所有控件以及包含控件的容器中的所有控件等等。VB.NET迭代通过控件容器

Form 
-Panel 
--Control 
--Tab 
----Control 
----Control 
--Tab 
----Control 

只检索 - 面板,没有其他控件

For Each cntrl As Control In Me.Controls 

Next 

我怎样才能找回他们都在一个For Each循环,而不下面的IF /然后在堆栈的每级?

编辑:

Dim ctl As Control = Me 
Do 
    ctl = Me.GetNextControl(ctl, True) 
    'Do whatever you have to ctl 
Loop Until ctl Is Nothing 

这是迄今为止我发现这样做的最佳方法。

+0

这就是我发现也是最好的。 – dbasnett 2011-12-17 13:36:27

回答

2

您必须定义一个方法,该方法将容器内部的容器穿过recursively。事情是这样的:

Dim _list As New List(Of Control) 
Public Sub GetChilds(container As Control) 
     For Each child As Control In container.Controls 
      _list.Add(child) 
      If (child.HasChildren) Then 
       GetChilds(child) 
      End If 
     Next 
End Sub 

要调用这个方法:

list=new List(Of Control) 
    GetChilds(Me) 
    For Each cntrl As Control In _list 
    .... 
    Next 
+0

我看到了作品。你怎么看待上面的编辑? – Theveloper 2011-12-17 03:00:13