Search code examples
vb.netcontrolspanelmulti-layer

How to access controls of Multilayer Panels in vb.net


I want to access all of the controls in my form with this code:

For each pc in Myform.control

do somthing

My Problem is that I have multilayer panels in myform.For example "Myform" contains (textbox1,textbox 2,combobox1,panle1,panel2).

Panel1 contains (panel11 and textbox 3)

panel 2 contains (panel22 and textbox4 and combobox2)

In addition panel22 contains (textbox5 and panle222)

How can I access "All" of the controls(textbox and combobox) in "Myform" without considering whether they are in a panel or not.

Any help is greatly appreciated.


Solution

  • Something like this should do it:

    Private Sub EnumerateControl(parentControl As Control)
        For Each child As Control In parentControl.Controls
            Debug.WriteLine(child.Name)
            If child.HasChildren Then EnumerateControl(child)
        Next
    End Sub
    

    Then call this to use it:

    EnumerateControl(Me) 'Pass the form control to start the enumeration
    

    The key here is to test if the control in question has children and if so enumerate all controls in that control by calling EnumerateControl recursively