Accessing Controls by Their Names or Indices

The preferred way to access controls is via the auto-generated member variables such as Me.TextBox1 in a form. The function FindControl takes a form or container control and a string containing the name of the control to be obtained and returns a reference to the control:

Private Function FindControl( _
    ByVal ControlName As String, _
    ByVal CurrentControl As Control _
) As Control
    For Each ctr As Control In CurrentControl.Controls
        If ctr.Name = ControlName Then
            Return ctr
        Else
            ctr = FindControl(ControlName, ctr)
            If Not ctr Is Nothing Then
                Return ctr
            End If
        End If
    Next ctr
End Function

Usage:

DirectCast(FindControl("Button1", Me), Button).Enabled = False

That the procedure listed above is rather slow. To access a lot of controls by name very often references to the controls can be stored in a Hashtable object. The name of the control is used as the key:

Private m_Controls As New Hashtable()

Adding a control:

Dim DynamicPictureBox As New PictureBox()
DynamicPictureBox.Name = "PictureBox1"
m_Controls.Add(DynamicPictureBox.Name, DynamicPictureBox)

Looking for a control:

Dim p As PictureBox = DirectCast(m_Controls.Item("PictureBox1"), PictureBox)

Removing a control:

m_Controls.Remove("PictureBox1")

Sometimes it is even better to add the controls to an array. This will allow fast and easy index-based access to the controls:

Dim MyLabels() As Label = {Label1, Label2, …, Label10}

Access by MyLabels(0) to MyLabels(9).

Control arrays as known from Visual Basic 6.0 are not available in Visual Basic .NET 2003 and Visual Basic 2005.