Visual Basic 6.0 Guide
Control Arrays

So far, the code that you have written is run when one item is clicked - often a button or listbox. Control arrays allow you to write one set of code that will work for each of the items in the array.

We can enhance the program that we wrote in the previous section by allowing the user to press the enter key after entering a number in one of the boxes. If the user presses enter in one of the first 4 boxes, we need to put the cursor in the box below. If they press enter in the fifth box, we want to run the code that is executed when we press the command button.

Double Click on one of the text boxes and the following lines appear in the code window.

Private Sub txtNumbers_Change(Index As Integer)

End Sub

You want to program the keypress event. Change the dropdown box in the top right of the code window so that it says keypress. You should then be able to enter the code below.

The variables Index and KeyAscii are automatically generated by Visual Basic. Index stores the number (index) of the text box in which the event takes place. KeyAscii stores the Ascii number (how the computer stores characters) of the key that has been pressed.

The number 13 represents the Enter key. If this is pressed and the text box is any but the last one (4), then the cursor is placed in the next box. If the index is 4 (the last box), the command button procedure is called.

Private Sub txtNumbers_KeyPress(Index As Integer, KeyAscii As Integer)
If KeyAscii = 13 And Index < 4 Then
txtNumbers(Index + 1).SetFocus
ElseIf KeyAscii = 13 And Index = 4 Then
cmdDisplay_Click
End If
End Sub