Developer

Iterating through all controls on the form with VB.NET

Irina Medvinskaya presents a simple way to change all the controls on a form in runtime with VB.NET.

If you've ever had to change all the controls on a form in runtime, you know how tedious it can be to modify the controls one by one. Here's a simple way to perform this useful function with VB.NET.

Controls collection

The form maintains a collection of controls that you can utilize to loop through in order to change a certain property that you want to update in runtime.

For example, add two textboxes to a form and add the following code:

Private Sub SetControls()
        Dim cControl As Control
        For Each cControl InMe.Controls
            If (TypeOf cControl Is TextBox) Then
                cControl.Text = "abc"
            End If
        Next cControl
    End Sub

Figure A shows what you will see when you run the code.

Figure A

In the example, I define the variable cControl as a Control object. I then create a for loop that will check all the controls on the form to see if the type of the control is a TextBox. For all the TextBox controls, I set its Text property to value "abc"; so, the Text property would be set to "abc" for as many TextBox controls as you have on the form. You can follow a similar procedure for setting other properties or use it for different control types.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks