What is the best way to traverse all controls on a form in vb2005

What's the best way to go through all the controls on a form in vb2005? I am writing a program that can edit a byte string based on form information. each control is tagged with a hexadecimal address that it modifies and the values ​​it can be, what is the best way to go through all the controls on the form, even those controls embedded in other controls?

+1


a source to share


4 answers


Something like this, passing in a 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

      

+6


a source


Get an instance of System.Windows.Forms.Control.ControlCollection (Me.Controls) from the current form. Then from there through the controls in the collection.



+1


a source


This is C # but should give an idea. The function just recursively lists all the controls, and you can do whatever you want with them.

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 will be something like this.

foreach (Control control in GetControlsRecursive(myForm))
{
    DoStuff(control);
}

      

Solution Without an operator yield return

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

      

+1


a source


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

      

0


a source







All Articles