Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

298 Part II Programming Fundamentals


Referencing Objects in a Collection


You can reference the objects in a collection, or the individual members of the collection,
by specifying the index position of the object in the group. Visual Basic stores collection
objects in the reverse order of that in which they were created, so you can use an object’s
“birth order” to reference the object individually, or you can use a loop to step through
several objects. For example, to identify the last object created on a form, you can specify
the 0 (zero) index, as shown in this example:
Controls(0).Text = "Business"
This statement sets the Text property of the last object on the form to “Business .” (The
second-to-last object created has an index of 1, the third-to-last object created has an index
of 2, and so on .) Considering this logic, it’s important that you don’t always associate a
particular object on the form with an index value because if a new object is added to the
collection, the new object takes the 0 index spot and the remaining object indexes are
incremented by 1.
The following For... Next loop uses a message box to display the names of the last four
controls added to a form:
Dim i As Integer
For i = 0 To 3
MsgBox(Controls(i).Name)
Next i
Note that I’ve directed this loop to cycle from 0 to 3 because the last control object added to
a form is in the 0 position. In the following section, you’ll learn a more efficient method for
writing such a loop.

Writing For Each Next Loops


Although you can reference the members of a collection individually, the most useful way
to work with objects in a collection is to process them as a group. In fact, the reason that
collections exist is so that you can process groups of objects efficiently. For example, you
might want to display, move, sort, rename, or resize an entire collection of objects at once.
To handle this kind of task, you can use a special loop called For Each... Next to cycle
through objects in a collection one at a time. A For Each... Next loop is similar to a
For... Next loop. When a For Each... Next loop is used with the Controls collection, it
looks like this:
Dim CtrlVar As Control
...
For Each CtrlVar In Controls
process object
Next CtrlVar
The CtrlVar variable is declared as a Control type and represents the current object in the
For Each... Next loop. Controls (note the “s”) is the collection class that I introduced earlier
that represents all the control objects on the current form. The body of the loop is used to
Free download pdf