Sams Teach Yourself Visual Basic 6 in 24 Hours

Sams Teach Yourself Visual Basic 6 in 24 Hours

By Greg Perry

Control Arrays

A control array is a list of controls with the same name. Instead of using four command buttons with four separate names, you can place a command button control array on the form, and that control array holds four command buttons. The control array can have a single name, and you'll distinguish the controls from each other with a subscript.

One of the best reasons to use a control array is that you can add the first control to your form and set all its properties. When you create a control array from that first control, all the elements in the control array take on the same property values. You then can change those properties that need to be changed without having to set every property for every control individually.

A control array is an array of several controls that you reference with an Index property value that acts as the subscript. The controls in a control array must be of the same control type.

Control arrays have a lot in common with data arrays. A control array has one name, and you distinguish all the array's controls from each other with the zero-based subscript. (The Index property holds the control's subscript number.) All the control array elements must be of the same datatype.

As soon as you place a control on a form that has the same name as an existing control, Visual Basic makes sure that you want to begin a control array by issuing the warning message shown in Figure 10.7. The message box keeps you from accidentally creating a control array when you actually want to add a different control. You'll see Figure 10.7's message box when you copy an existing control to the Clipboard and paste the copy elsewhere onto the form. If you click No, Visual Basic uses a default control name for the placed control.

10fig07.gif

Figure 10.7 Visual Basic asks whether you want a control array.

All event procedures that use controls from a control array require a special argument value passed to them to determine which control is being worked on. For example, if your application contains a single command button named cmdTotal, the Click() event procedure begins and ends as follows:

Private Sub cmdTotal_click ()

End Sub

If, however, you created a control array named cmdTotal, the Click() event procedure begins and ends like this:

Private Sub cmdTotal_click (Index As Integer)

End Sub

The procedure uses the Index argument as the control index number (the subscript) that the user clicked. If you want to change the clicked command button's Caption property inside the cmdTotal_Click() procedure, you would do so like this:

cmdTotal(Index).Caption = "A new Caption value"

The Index value holds the command button's index that the user clicked to generate the event procedure. You will always respond to the proper clicked control if you use Index after the control array name.

Share ThisShare This

Informit Network