CONTROL ARRAYS

 

Similar to arrays of variables, you can group a set of controls together as an array. The following facts apply to control arrays:

 

 

 

 

 

ControlName(Index)[.Property]

 

For example, to refer to the Text property of the first element of an array of textboxes called txtField, you would use:

 

      txtField(0).Text

 

 

Private Sub txtField_GotFocus(Index As Integer)

 

    txtField(Index).SelStart = 0

    txtField(Index).SelLength = Len(txtField(Index).Text)

 

End Sub

 

            - or -

 

Private Sub txtField_GotFocus(Index As Integer)

 

    With txtField(Index)

        .SelStart = 0

        .SelLength = Len(.Text)

    End With

 

End Sub

 

For events where VB already passes a parameter (for example, the textbox's KeyPress event where VB passes the KeyAscii parameter), VB will add "Index" as the first parameter, followed by the parameters that are usually passed to the event. For example, the procedure header of the KeyPress event of the txtField control array would look like this:

 

      Private Sub txtField_KeyPress(Index As Integer, KeyAscii As Integer)

 

 

To build a sample application that uses a control array, perform the following steps:

 

 

Property          Value

(Name)            cmdTest

Caption           First

 

            At this point your form should look like this:

 

 

 

 

 

 

 

 

Private Sub cmdTest_Click(Index As Integer)

 

    Print cmdTest(Index).Caption

 

End Sub

 

 

 

 

 

Download the VB project code for the example above here.