For Each

A specialized form of For loop in Visual Basic allows us to repeat a set of statements for each element in a collection.

A collection contains references to one or more objects. The objects may or may not be of the same type. The Controls Collection for a Form contains references to all the controls on a form (command buttons, text boxes, and labels).

It is important to remember that a collection contains a list of references to objects NOT the objects themselves.

 

Format of the For Each Statement

Dim varElement As DataType

For Each varElement In varCollection

one or more statements

Next varElement

 

Where varElement is a variable that represents each element in the collection and varCollection refers to the collection that you wish to access.


For example


Dim curCheckBox As CheckBox

For Each curCheckBox In grpStatus.Controls
        curCheckBox.Checked = False
Next

Will set the Checked property of all the CheckBoxes in the the Group control grpStatus to False.

 

If an object in the collection is NOT does not support the property Checked an error will occur.

 

For Each Exception

 

The GetType method can be used to determine if a generic object in a collection is the desired datatype and the Ctype( ) function can be used to convert an object to the desired datatype.

Dim curObject As Object
Dim
curCheckBox As CheckBox

For Each curObject In grpStatus.Controls
        If curObject.GetType.ToString = "System.Windows.Forms.CheckBox" Then
            curCheckBox = CType(curObject, CheckBox)
            curCheckBox.Checked = False
        End If
Next