Whats the best way to go through all the controls on a form in vb2005? Im writing a program that can edit a string of bytes based on the information on the form. each control is tagged with the hex address it modifies and values it can be, what is the best way to go through all the controls on a form even those controls embedded in other controls?
+6
A:
Something like this, passing in the form to start with:
Private Sub DoSomethingToAllControls(ByVal Container As Control)
Dim ctl As Control
For Each ctl In Container.Controls
' Do Something..
' Recursively call this function for any container controls.
If ctl.HasChildren Then
DoSomethingToAllControls(ctl)
End If
Next
End Sub
Stuart Dunkeld
2009-05-26 22:48:43
+1
A:
Get the instance of System.Windows.Forms.Control.ControlCollection (Me.Controls) from the current form. The from there step through the controls in the collection.
dtoland
2009-05-26 22:54:32
+1
A:
This is C#, but should give the idea. The function just recursivly enumerates all controls and you can do with them what ever you want.
public static IEnumerable<Control> GetControlsRecursive(Control control)
{
yield return control;
foreach (Control directSubcontrol in control.Controls)
{
foreach (Control subcontrol in GetControlsRecursive(directSubcontrol))
{
yield return subcontrol;
}
}
}
The usage would be something like this.
foreach (Control control in GetControlsRecursive(myForm))
{
DoStuff(control);
}
Solution Without the yield return
statement not availiable in VB.NET.
public static IEnumerable<Control> GetControlsRecursive(Control control)
{
List<Control> controls = new List<Control>() { control };
foreach (Control subcontrol in control.Controls)
{
controls.AddRange(GetControlsRecursive(subcontrol));
}
return controls;
}
Daniel Brückner
2009-05-26 23:01:50
He asked for VB.Net
Joel Coehoorn
2009-05-26 23:03:11
"This is C#, but should give the idea." And the lack of the yield return statement in VB.NET won't change the basic idea - it just requires to explicitly construct a list.
Daniel Brückner
2009-05-26 23:09:25
A:
Private Sub enumerateControls(ByVal controlcontainer As Object)
Dim basec As Control = controlcontainer
If basec.HasChildren Then
For Each itm As Control In basec.Controls
enumerateControls(itm)
Next
End If
If controlcontainer.tag IsNot Nothing Then
run function to determine control type and function
End If
End Sub
Jim
2009-05-26 23:20:33