Jim
Jim

Reputation: 601

Whats the best way to go through all the controls on a form in vb2005

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?

Upvotes: 1

Views: 243

Answers (4)

Jim
Jim

Reputation: 601

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

Upvotes: 0

Daniel Brückner
Daniel Brückner

Reputation: 59705

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;
}

Upvotes: 1

dtoland
dtoland

Reputation: 116

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.

Upvotes: 1

stuartd
stuartd

Reputation: 73303

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

Upvotes: 6

Related Questions