Enumerate All Form Controls - Even Nested Ones
A simple Sub to enumerate all the controls on a form even if they are nested as children of other controls. For example, say you add a GroupBox to your form and then add a Checkbox, this won't work:
VB Code:
For Each ctl as Control in Me.Controls
If TypeOf ctl Is CheckBox Then
' Won't find the CheckBox
End If
Next
You need a recursive Sub:
VB Code:
Private Sub EnumControls(ByVal ctl As Control)
MessageBox.Show(ctl.Name)
If ctl.HasChildren Then
For Each c As Control In ctl.Controls
EnumControls(c)
Next
End If
End Sub
So you can call the Sub on Form_Load as EnumControls(Me). You can also test for a type of control:
VB Code:
Private Sub EnumControls(ByVal ctl As Control)
If TypeOf ctl Is CheckBox Then
MessageBox.Show(ctl.Name)
End If
If ctl.HasChildren Then
For Each c As Control In ctl.Controls
EnumControls(c)
Next
End If
End Sub