By default, every control on a Visual Basic 6 form is an independent entity with its own name and its own event procedures. In some situations, you can simplify your programming work by using a control array. This permits two or more controls of the same type to have the same name and same event procedures but retain their own separate properties. This tip shows you how.
To create a control array, you must put a single control of the desired type on the form. With the control selected, press [Ctrl]C and then [Ctrl]V. Visual Basic will display the following prompt:You already have a control named XXXXX. Do you want to create a control array?
Click Yes. Now you'll have two identical controls--Command Buttons, Check Boxes, or whatever--on the form. Repeat the steps to add more controls to the array. (There is no limit to the size of a control array other than those imposed by system resources, although you'll rarely find arrays of more than 8-12 controls to be useful.)
When you select a control in an array, the Properties window displays its properties. Except for the Name, these properties are completely independent from other controls in the array. If all the controls have the same name, how can you tell them apart? The answer lies in the Index property. The first control in an array has Index = 0, the second control has Index = 1, and so on. Controls that aren't part of an array have a blank Index property.
As I mentioned, all the controls in an array share the same event procedures. The procedure is passed an argument indicating the Index property of the control that received the event. This is where the usefulness of control arrays is most evident. You can write a single event procedure that handles the events for multiple controls. For example, you could create an array of three Command Button controls and then write the Click event procedure as follows:Private Sub Command1_Click(Index As Integer)
Select Case Index
' Code for first action here.
' Code for second action here.
' Code for third action here.
Keeping code together like this rather than spreading it out over multiple event procedures makes it easier to write and debug.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!