• 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!

    more

Translate

Google-Translate-Chinese (Simplified) BETA Google-Translate-English to French Google-Translate-English to German Google-Translate-English to Italian Google-Translate-English to Japanese BETA Google-Translate-English to Korean BETA Google-Translate-English to Russian BETA Google-Translate-English to Spanish

Tags