-
How to loop through all controls on a form
There are times when a developer needs to loop through all of the controls on the form. Initially, a recursive method comes to mind, however, with VB.NET, it’s really a lot easier than you think.
In a regular Windows Forms Application, where “Me” represents the form, use the following snippet of code to loop through all controls on the form, even controls nested in various layers of panels, group boxes, etc.:
Dim ctl As Control = Me
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then _
MessageBox.Show(ctl.Name)
Loop Until ctl Is Nothing
If you are looking for a control of a particular type, then just check for that type, and then perform your desired actions:
Dim ctl As Control = Me
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then
' Search for a TextBox
If TypeOf ctl Is TextBox Then _
MessageBox.Show(ctl.Name)
End If
Loop Until ctl Is Nothing
And that’s all there is to it!
Subscribe to:
Posts (Atom)