Iterating on the Items of a Control Array

Started by sukishan, Jul 16, 2009, 02:56 PM

Previous topic - Next topic

sukishan

Iterating on the Items of a Control Array
Control arrays often let you save many lines of code because you can execute the same statement, or group of statements, for every control in the array without having to duplicate the code for each distinct control. For example, you can clear the contents of all the items in an array of TextBox controls as follows:

For i = txtFields.LBound To txtFields.UBound
txtFields(i).Text = ""
Next

Here you're using the LBound and UBound methods exposed by the control array object, which is an intermediate object used by Visual Basic to gather all the controls in the array. In general, you shouldn't use this approach to iterate over all the items in the array because if the array has holes in the Index sequence an error will be raised. A better way to loop over all the items of a control array is using the For Each statement:

Dim txt As TextBox
For Each txt In txtFields
txt.Text = ""
Next

A third method exposed by the control array object, Count, returns the number of elements it contains. It can be useful on several occasions (for example, when removing all the controls that were added dynamically at run time):

' This code assumes that txtField(0) is the only control that was
' created at design time (you can't unload it at run time).
Do While txtFields.Count > 1
Unload txtFields(txtFields.UBound)
Loop
A good beginning makes a good ending