Using a control array in a Visual Basic form
Whenever you have to design a form with several controls that do the same thing, consider using a
control array.
A control array is not an array that controls, it's an array of controls.
In the Invoicing example from the previous lesson, we must have 3 textboxes for items and 3 textboxes for prices. We'll create 2 control arrays - one for items and one for prices.
Creating a control array is really simple:
- create the first textbox
- give the textbox the appropriate Name property
- copy the first textbox
- paste the textbox onto the form
- answer 'Yes' when asked if you want to create a control array
The biggest advantage of creating a control array is that you can then use the looping structures to manipulate them.
If, for example, I wish to clear 3 textboxes defined in an array, I use a For...Next construct:
For i = 0 To 2
txtItems(i).Text = ""
txtPrices(i).Text = 0
Next
Note that the index for an array starts at 0. You always increment index values from 0 to n-1, where n is the number of elements in the array.
If I decide to use 10 textboxes for items and prices, I can use the same code, but change the index:
For i = 0 To 9
txtItems(i).Text = ""
txtPrices(i).Text = 0
Next

Previous
Next