How to create Control Arrays in VB .NET

Solution 1:

Here is a sample I wrote for something else that shows how to do something similar and shows how to do the handler as well. This makes a 10x10 grid of buttons that turn red when you click them.

Dim IsCreated(99) As Boolean
Dim Buttons As New Dictionary(Of String, Button)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    For i As Integer = 0 To 99
        Dim B As New Button
        Me.Controls.Add(B)
        B.Height = 30
        B.Width = 40
        B.Left = (i Mod 10) * 41
        B.Top = (i \ 10) * 31
        B.Text = Chr((i \ 10) + Asc("A")) & i Mod 10 + 1
        Buttons.Add(B.Text, B)
        B.Tag = i
        AddHandler B.Click, AddressOf Button_Click
    Next


End Sub

Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim B As Button = sender
    IsCreated(B.Tag) = True
    B.BackColor = Color.Red
End Sub

Solution 2:

Avoid using the proposed iteration approaches, you'll get a fairly random collection of controls unless your form is very simple. Simply declare the control array in your code and initialize it in the form constructor. Like this:

Public Class Form1
    Private OrderNumbers() As TextBox

    Public Sub New()
        InitializeComponent()
        OrderNumbers = New TextBox() {TextBox1, TextBox2}
    End Sub
End Class

You can now treat OrderNumbers just like you could in VB6.

Solution 3:

Maybe this is simpler. To create a control array, I put the control array declaration in a module. For example, if I have a Form with three TextBoxes and I want the TextBoxes to be part of a control array called 'mytext', I declare my control array in a module as follows:

Module Module1

Public mytext() As TextBox = {Form1.TextBox1, Form1.TextBox2, Form1.TextBox3}

End Module

And, I use the TextBoxes from the control array as follows:

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    mytext(0).Text = "Hello"
    mytext(1).Text = "Hi"
    mytext(2).Text = "There"

End Sub

End Class

You can even loop through the control array, like you could in VB6:

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    For i As Integer = 0 To 2
        mytext(i).Text = i + 1
    Next

End Sub

End Class

The beauty of using a module is that the TextBoxes do not even need to be in the same form.

Solution 4:

With Winforms, you could do this:

myForm.Controls _
  .OfType(Of TextBox) _
  .OrderBy(Function(c) c.Name) _
  .Where(Function(c) c.Name.StartsWith("somePrefix")) _
  .ToArray()

On your form you would name your textboxes somePrefix1, somePrefix2, etc.

Here is an old article but it could give you more information. The top method is super easy.