1. Herfried K. Wagner’s VB.Any
  2. .NET
  3. Frequently Asked Questions

Accessing controls by their names or indices

Accessing controls by their names or indices
<URL:https://dotnet.currifex.org/dotnet/faqs/controlbynameindex/en/>
----------------------------------------------------------------------------

Accessing controls by their names or indices

\\\
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
///

Notice that the procedure listed above is "slow", if you have to access a
lot of controls by name very often, you should store references to them in a
'Hashtable' object.  You can use the name of the control as 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 control to an array.  This will
allow fast and easy index-based access to the control references:

\\\
Dim MyLabels() As Label = {Label1, Label2, ..., Label10}
///

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

Control arrays:

Control arrays, as known from Visual Basic 6.0, are not included in Visual
Basic .NET 2002/2003 and Visual Basic 2005.

Creating Control Arrays in Visual Basic .NET and Visual C# .NET
<URL:http://msdn.microsoft.com/library/en-us/dv_vstechart/html/vbtchCreatingControlArraysInVisualBasicNETVisualCNET.asp>

Getting Back Your Visual Basic 6.0 Goodies
<URL:http://msdn.microsoft.com/library/en-us/dnadvnet/html/vbnet05132003.asp>

WinForms Controls--Creating Control Arrays in VB.NET
<URL:http://www.devx.com/vb2themax/Article/19907/>

Control Array
<URL:http://www.windowsforms.net/ControlGallery/ControlDetail.aspx?Control=251&tabindex=5>