tags:

views:

106

answers:

4

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
+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
+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
He asked for VB.Net
Joel Coehoorn
"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
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