Control Arrays

Download a sample VB program that uses an array of controls.

Instructions for Creating the Example:

  1. Start Visual Basic from the Start menu.
  2. Select Standard EXE, and click Open.
  3. VB should now show a window with: the Toolbox, a Form, the Project Explorer, and the Properties Window.
  4. Place the following widgets on your form: one command button, four labels , and three textboxes .  Select them from the toolbar and then draw a rectangle on the form.  You can move them around and resize them as you like.
  5. Set the following properties of each object in the properties toolbar:
Command Button 1 Label 1 Label 2 Label 3 Label 4
Name cmdClear lblName lblAddress lblPhone lblEvent
Caption Clear All Name Address Phone Event info will show up here

All three textboxes will have the same name, but each will be assigned a different index value.  We can later use the index value to uniquely identify each textbox, just like an element in an ordinary array.

Text Box 1 Text Box 2 Text Box 3
Name txtData txtData txtData
Index 0 1 2

It should look something like this:

  1. We are ready to add some code now.  Double click on any of the textboxes.  Because each textbox belongs to the same array, they will all use the same code.  You can check the Index parameter that gets passed to the subroutine to see which object actually received the event.  Add the following code to any of the textboxes:

Private Sub txtData_Change(Index As Integer)

    lblEvent.Caption = "You typed in textbox " & Index

End Sub

  1. Now add this code to the Clear All button's click event:

Private Sub cmdClear_Click()

    ' clear each textbox in the array of textboxes
    For i = 0 To 2
        txtData(i).Text = ""
    Next

    ' an equivalent while loop would be:
    i = 0
    While i < 3
        txtData(i).Text = ""
        i = i + 1
    Wend

End Sub

  1. To run your program, click on the Play button in the toolbar under the menu.