Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 12 Working with Collections 303


Tip If you plan to give several objects special treatment in a For Each... Next loop, you can use
ElseIf statements with the If... Then statement, or you can use a Select Case decision structure.

In the following exercise, you’ll test the Name property of the third button object
(btnMoveObjects) to give that button special treatment in a For Each... Next loop. The result
will be an event procedure that moves the top two buttons to the right but keeps the bottom
button stationary.

Tip In addition to the Name property, most objects support the Tag property. Similar to the
Name property, the Tag property is a location in which you can store string data about the
object. The Tag property is empty by default, but you can assign information to it and test it to
uniquely identify objects in your program that you want to process differently.

Use the Name property to give an object in the Controls collection special treatment


  1. Display the form, and then double-click the third button object.


The btnMoveObjects_Click event procedure appears in the Code Editor. Remember that
you changed the Name property of this object from “Button3” to “btnMoveObjects” in
an earlier exercise.


  1. Type the following program code in the event procedure:


For Each ctrl In Controls
If ctrl.Name <> "btnMoveObjects" Then
ctrl.Left = ctrl.Left + 25
End If
Next
The new feature of this For Each... Next loop is the If... Then statement that checks
each collection member to see whether it has a Name property called “ btnMoveObjects .”
If the loop encounters this marker, it passes over the object without moving it. Note that,
as in the previous examples, the ctrl variable was declared at the top of the form as a
variable of the Control type with scope throughout the form.


  1. Click the Save All button to save your edits.


Tip The complete Controls Collection program is located in the C:\Vb10sbs\Chap12\
Controls Collection folder.


  1. Click the Start Debugging button.


The program runs, and the three button objects appear on the form.
Free download pdf