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.
- Save these images in your folder: Shell.wmf and Pearl.wmf.
- Begin by designing the form.
- Create a single image named
imgShell
with an Index of 0. Find the Shell.wmf file you downloaded for the Picture property. - Copy and paste the images to create 3 images as part of a control array.
- Use the same method to create a three-image control array named
imgPearl
. - Create
cmdDone
and add code to it. - 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. - 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() Private Sub imgShells_Click(Index As Integer) |