Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Visual Basic
Article

The Closest thing to a VB6 control array in VB.NET

Rate me:
Please Sign up or sign in to vote.
3.21/5 (18 votes)
26 Apr 20072 min read 161.8K   1.5K   36   26
With a single method call, turn all your controls on a form into a control array.

Introduction

Any VB programmer who has moved to VB.NET knows the frustration of losing the ability to create control arrays in a form. VB.NET adds a great amount of flexibility and power, but at the cost of losing some of the features that made VB a great rapid development environment that hid many of the programming details from the developer. One such loss is the control arrays. In the past, you could drop a number of controls on the screen with the same name, and VB took care of creating a member variable for you, so that you could reference the controls as an array within your code. VB.NET has not done this for you yet.

Here is a very simple solution that links the controls on the form to a member variable in your code, which gives you the closest thing to a VB control array, using one function call. The only constraint is that you must follow a naming convention for your controls. NameXXX where 'Name' is any string name you would like for this group of controls and XXX is an integer value representing the index of the array it is to be assigned to.

For example, if you have five TextBoxes on the screen, you would name them as follows:

myTextBox0
myTextBox1
myTextBox2
myTextBox3
myTextBox4

The function included in the sample project will then search the form for myTextBoxXXX, strip off the index and assign it to a control array for you. A sample call to create the control array is as follows:

VB
Dim textBoxes As TextBox() = _
     ControlArrayUtils.getControlArray(Me, "myTextBox")

That's it. You can then use TextBoxes in your code to do whatever you need.

VB
Dim mTextBoxes() As TextBox
Private Sub Form1_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
    mTextBoxes = ControlArrayUtils.getControlArray(Me, "TextBox")
    mTextBoxes(1).Text = "Form Load Test 1"
end sub
Dim mTextBoxes() as TextBox
Private Sub Form1_Load(ByVal sender as System.Object, _
           ByVal e as System.EventArgs) Handles MyBase.Load
    Dim ii as integer
    myTextBoxes = ControlArrayUtils.getControlArray(Me."TextBox")
    for ii=1 to 5
        myTextBoxes(ii).Text = ii
    next ii
end sub

You can also declare the TextBoxes array as a member variable of your form, and then call this function once in the Form_Load event. The array will then be ready for use anywhere on the form after that, giving almost identical functionality as the VB6 method. The current implementation looks only for controls on the Form. But it is possible to do a recursive search or a search on a specific control. This will come later.

The ControlArrayUtils code is listed below and is downloadable as a demo:

VB
Public Class ControlArrayUtils

    'Converts same type of controls on a form to a control 
    'array by using the notation ControlName_1, ControlName_2, 
    'where the _ can be replaced by any separator string
    
    Public Shared Function getControlArray(_
         ByVal frm As Windows.Forms.Form, _
         ByVal controlName As String, _
         Optional ByVal separator As String = "") As System.Array
    
      Dim i As Short
      Dim startOfIndex As Short
      Dim alist As New ArrayList
      Dim controlType As System.Type
      Dim ctl As System.Windows.Forms.Control
      Dim ctrls() As System.Windows.Forms.Control
      Dim strSuffix As String
      Dim maxIndex As Short = -1 'Default
       
    
    'Loop through all controls, looking for 
    'controls with the matching name pattern
    'Find the highest indexed control
    
      For Each ctl In frm.Controls
        startOfIndex = ctl.Name.ToLower.IndexOf(_
                        controlName.ToLower & separator)
        If startOfIndex = 0 Then
            strSuffix = ctl.Name.Substring(controlName.Length)
            'Check that the suffix is an
            ' integer (index of the array)
            If IsInteger(strSuffix) Then 
                If Val(strSuffix) > maxIndex Then _
                   maxIndex = Val(strSuffix) 'Find the highest 
                                             'indexed Element
            End If
        End If
      Next ctl
    
      'Add to the list of controls in correct order
      If maxIndex > -1 Then
    
        For i = 0 To maxIndex
            Dim aControl As Control = _
              getControlFromName(frm, controlName, i, separator)
            If Not (aControl Is Nothing) Then
                'Save the object Type (uses the last 
                'control found as the Type)
                controlType = aControl.GetType       
            End If
            alist.Add(aControl)
        Next
      End If
      Return alist.ToArray(controlType)
    End Function
    
    'Converts any type of like named controls on a form 
    'to a control array by using the notation ControlName_1, 
    'ControlName_2, where the _ can be replaced by any 
    'separator string
    
    Public Shared Function getMixedControlArray(_
       ByVal frm As Windows.Forms.Form, ByVal controlName As String, _
       Optional ByVal separator As String = "") As Control()
    
    Dim i As Short
    Dim startOfIndex As Short
    Dim alist As New ArrayList
    Dim controlType As System.Type
    Dim ctl As System.Windows.Forms.Control
    Dim ctrls() As System.Windows.Forms.Control
    Dim strSuffix As String
    Dim maxIndex As Short = -1 'Default
    
    'Loop through all controls, looking for controls 
    'with the matching name pattern
    'Find the highest indexed control
    
        For Each ctl In frm.Controls
            startOfIndex = ctl.Name.ToLower.IndexOf(_
                          controlName.ToLower & separator)
            If startOfIndex = 0 Then
                strSuffix = ctl.Name.Substring(controlName.Length)
                'Check that the suffix is an integer 
                '(index of the array)
                If IsInteger(strSuffix) Then 
                    If Val(strSuffix) > maxIndex Then _
                       maxIndex = Val(strSuffix) 'Find the highest 
                                                 'indexed Element
                End If
            End If
        Next ctl
    
    'Add to the list of controls in correct order
        If maxIndex > -1 Then
            For i = 0 To maxIndex
                 Dim aControl As Control = getControlFromName(frm, _
                                          controlName, i, separator)
                 alist.Add(aControl)
            Next
        End If
        Return alist.ToArray(GetType(Control))
    End Function
    
    Private Shared Function getControlFromName(_
           ByRef frm As Windows.Forms.Form, _
           ByVal controlName As String, ByVal index As Short, _
           ByVal separator As String) As System.Windows.Forms.Control
        controlName = controlName & separator & index
        For Each ctl As Control In frm.Controls
           If String.Compare(ctl.Name, controlName, True) = 0 Then
               Return ctl
           End If
        Next ctl
        Return Nothing 'Could not find this control by name
    End Function
    
    Private Shared Function IsInteger(ByVal Value As String) As Boolean
        If Value = "" Then Return False
        For Each chr As Char In Value
            If Not Char.IsDigit(chr) Then
                Return False
            End If
        Next
        Return True
    End Function
End Class

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow about an event handler? Pin
RJW858-Feb-17 6:19
RJW858-Feb-17 6:19 
QuestionControls in a Container or Tab Control Pin
bobmori7-Nov-14 4:51
bobmori7-Nov-14 4:51 
GeneralMy vote of 5 Pin
paruluscorilo28-Aug-12 22:01
paruluscorilo28-Aug-12 22:01 
GeneralMy vote of 5 Pin
ed-clift18-Jul-12 13:17
ed-clift18-Jul-12 13:17 
Questioncontrol arrays and groupboxes Pin
Member 890411029-Apr-12 15:57
Member 890411029-Apr-12 15:57 
SuggestionRe: control arrays and groupboxes Pin
divopt12-Sep-12 5:49
divopt12-Sep-12 5:49 
GeneralExcellent article 10/10 Pin
dhuang88813-Dec-10 21:18
dhuang88813-Dec-10 21:18 
GeneralMy vote of 5 Pin
Warish Jain1-Oct-10 1:51
Warish Jain1-Oct-10 1:51 
GeneralControl Arrays ARE nice Pin
GMorris28-Aug-08 8:58
GMorris28-Aug-08 8:58 
Generalusing this with power pack 2.0 ovalshape Pin
Rcbuck5-Dec-07 0:24
Rcbuck5-Dec-07 0:24 
Generalre Pin
exiletgm31-Jul-07 9:08
exiletgm31-Jul-07 9:08 
GeneralNew support for controls not directly on form. [modified] Pin
kepler774-May-07 7:14
kepler774-May-07 7:14 
GeneralRe: New support for controls not directly on form. Pin
Member 219595718-Feb-11 14:49
Member 219595718-Feb-11 14:49 
GeneralThank you for a nice and helpful solution Pin
Alejandro Quiroga Alsina12-Apr-07 6:09
Alejandro Quiroga Alsina12-Apr-07 6:09 
GeneralRe: Thank you for a nice and helpful solution Pin
kepler7721-May-07 12:40
kepler7721-May-07 12:40 
GeneralVB6 is sooooo 1990's Pin
Carl Mercier15-Sep-05 4:29
Carl Mercier15-Sep-05 4:29 
GeneralRe: VB6 is sooooo 1990's Pin
jemmyw17-Sep-05 7:37
jemmyw17-Sep-05 7:37 
GeneralRe: VB6 is sooooo 1990's Pin
Lie129629-Nov-06 3:40
Lie129629-Nov-06 3:40 
GeneralRe: VB6 is sooooo 1990's Pin
Sarah249-May-07 22:13
Sarah249-May-07 22:13 
GeneralRe: VB6 is sooooo 1990's Pin
askhak14-May-07 17:12
askhak14-May-07 17:12 
GeneralRe: VB6 is sooooo 1990's Pin
m2s8721-Jul-07 20:50
m2s8721-Jul-07 20:50 
GeneralRe: VB6 is sooooo 1990's Pin
Lie129617-Jun-07 10:19
Lie129617-Jun-07 10:19 
GeneralRe: VB6 is sooooo 1990's Pin
Mitchster6-Jun-09 7:45
Mitchster6-Jun-09 7:45 
GeneralRe: VB6 is sooooo 1990's Pin
Alejandro Quiroga Alsina12-Apr-07 5:57
Alejandro Quiroga Alsina12-Apr-07 5:57 
GeneralRe: VB6 is sooooo 1990's Pin
askhak2-May-07 2:06
askhak2-May-07 2:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.