Control Arrays

Control Arrays

Controls are objects we put on a form, like command buttons, labels, text boxes, and option buttons. Normal controls must have unique names (a different name for each control) so that they can be identified in your code.

A control array is a set of controls, all the same type and with the same name. To uniquely identify them each one has an index number.

For example, the following form has three buttons that are part of a control array. Each button has the same name: cmdButton. Since they have the same name, they must have unique indexes: 0, 1, and 2. The caption on each button is the same as its index in this case.

Each element of the control array has the same set of code. A built-in variable called Index is passed to the subroutine so you know which element was clicked. The code in Example 1 is used to make the above program work.

Example 1
Private Sub cmdButton_Click(Index As Integer)
    ' display message
    lblMessage.Caption = "Button " & CStr(Index) & " clicked."
End Sub

Class Exercise: Shell Game

We will make a game like the carnival shell game, where the user must guess which shell has the pearl hidden below.

  1. Save these images in your folder: Shell.wmf and Pearl.wmf.
  2. Begin by designing the form.
  3. Create a single image named imgShell with an Index of 0. Find the Shell.wmf file you downloaded for the Picture property.
  4. Copy and paste the images to create 3 images as part of a control array.
  5. Use the same method to create a three-image control array named imgPearl.
  6. Create cmdDone and add code to it.
  7. Add code to Form_Load to initialize random numbers and hide all of the pearl images, using a For…Next loop to count from the lower to the upper bound of the control array.
  8. Add code to imgShell_Click that randomly chooses a shell to have the pearl hidden below, displays that pearl, and then displays a message if the user guessed correctly or incorrectly. Then it should hide the pearl.

Shell Game Code
Private Sub cmdDone_Click()
    ' end program
    Unload frmMain
End Sub

Private Sub Form_Load()
‘ dimension
Dim intIndex As Integer
‘ initialize random numbers
Randomize
‘ hide pearls
For intIndex = imgPearls.LBound To imgPearls.UBound
imgPearls(intIndex).Visible = False
Next intIndex
End Sub

Private Sub imgShells_Click(Index As Integer)
‘ dimension
Dim intSecretShell As Integer
‘ pick random location
intSecretShell = Int(Rnd * (imgShells.UBound + 1))
‘ show pearl
imgPearls(intSecretShell).Visible = True
‘ check for win
If intSecretShell = Index Then
Call MsgBox(“You found it!”)
Else
Call MsgBox(“Sorry.”)
End If
‘ hide pearl
imgPearls(intSecretShell).Visible = False
End Sub