Control array in VB.NET

Controls in .NET are just normal objects so you can freely put them into normal arrays or lists. The special VB6 construct of control arrays is no longer necessary.

So you can for example say,

Dim buttons As Button() = { Button1, Button2, … }

For Each button As Button In Buttons
    button.Text = "foo"
End For

Alternatively, you can directly iterate over the controls inside a container (e.g. a form):

For Each c As Control In MyForm.Controls
    Dim btt As Button = TryCast(c, Button)
    If btt IsNot Nothing Then ' We got a button!
        btt.Text = "foo"
    End If
End For

Notice that this only works for controls that are directly on the form; controls nested into containers will not be iterated this way; you can however use a recursive function to iterate over all controls.

Leave a Comment