Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 26 Apr 2007
Rate this:
Please Sign up or sign in to vote.
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:

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

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

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:

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

Share

About the Author

kepler77
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberparuluscorilo28-Aug-12 22:01 
GeneralMy vote of 5 Pinmembered-clift18-Jul-12 13:17 
Questioncontrol arrays and groupboxes PinmemberMember 890411029-Apr-12 15:57 
SuggestionRe: control arrays and groupboxes Pinmemberdivopt12-Sep-12 5:49 
GeneralExcellent article 10/10 Pinmemberdhuang88813-Dec-10 21:18 
GeneralMy vote of 5 PinmemberWarish Jain1-Oct-10 1:51 
GeneralControl Arrays ARE nice PinmemberGMorris28-Aug-08 8:58 
Generalusing this with power pack 2.0 ovalshape PinmemberRcbuck5-Dec-07 0:24 
Generalre Pinmemberexiletgm31-Jul-07 9:08 
GeneralNew support for controls not directly on form. [modified] Pinmemberkepler774-May-07 7:14 
GeneralRe: New support for controls not directly on form. PinmemberMember 219595718-Feb-11 14:49 
GeneralThank you for a nice and helpful solution PinmemberAlejandro Quiroga12-Apr-07 6:09 
GeneralRe: Thank you for a nice and helpful solution Pinmemberkepler7721-May-07 12:40 
GeneralVB6 is sooooo 1990's PinmemberCarl Mercier15-Sep-05 4:29 
GeneralRe: VB6 is sooooo 1990's Pinmemberjemmyw17-Sep-05 7:37 
GeneralRe: VB6 is sooooo 1990's PinmemberLie129629-Nov-06 3:40 
GeneralRe: VB6 is sooooo 1990's PinmemberSarah249-May-07 22:13 
GeneralRe: VB6 is sooooo 1990's Pinmemberaskhak14-May-07 17:12 
GeneralRe: VB6 is sooooo 1990's Pinmemberm2s8721-Jul-07 20:50 
GeneralRe: VB6 is sooooo 1990's PinmemberLie129617-Jun-07 10:19 
GeneralRe: VB6 is sooooo 1990's PinmemberMitchster6-Jun-09 7:45 
GeneralRe: VB6 is sooooo 1990's PinmemberAlejandro Quiroga12-Apr-07 5:57 
GeneralRe: VB6 is sooooo 1990's Pinmemberaskhak2-May-07 2:06 
AnswerRe: VB6 is sooooo 1990's Pinmemberm2s8721-Jul-07 18:05 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140922.1 | Last Updated 26 Apr 2007
Article Copyright 2005 by kepler77
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid