Working with Object Collections


Working with Object Collections

In this section, you'll learn about collections, a powerful mechanism for controlling objects and other data in a Visual Basic program. You already know that objects on a form are stored together in the same file. But did you also know that Visual Basic considers the objects to be members of the same group? In Visual Studio terminology, the entire set of objects on a form is called the Controls collection, which is part of the System.Collections namespace provided by the .NET Framework. The Controls collection is created automatically when you open a new form, and when you add objects to the form, they become part of that collection. In addition, Visual Studio maintains several standard object collections that you can use when you write your programs. In the rest of this chapter, you'll learn the basic skills you need to work with any collection you encounter.

Each collection in a program has its own name so that you can reference it as a distinct unit in the program code. For example, as you just learned, the collection containing all the objects on a form is called the Controls collection. This grouping method is similar to the way arrays group a list of elements together under one name, and like Visual Basic arrays, the Controls collection is zero-based.

If you have more than one form in a project, you can create public variables associated with the form names and use those variables to differentiate one Controls collection from another. (You'll learn more about using public variables to store form data in Chapter 14, “Managing Windows Forms and Controls at Run Time.”) You can even add controls programmatically to the Controls collection in a form.

In addition to working with collections and objects in your own programs, you can use Visual Studio to browse your system for other application objects and use them in your programs.

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-the-last object created has an index of 1, the third-to-the-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 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 I introduced earlier that represents all the control objects on the current form. The body of the loop is used to process the individual objects of the collection. For example, you might want to change the Enabled, Left, Top, Text, or Visible properties of the objects in the collection, or you might want to list the name of each object in a list box.

Experimenting with Objects in the Controls Collection

In the following exercises, you'll use program code to manipulate the objects on a form by using the Controls collection. The project you'll create will have three button objects, and you'll create event procedures that change the Text properties of each object, move objects to the right, and give one object in the group special treatment. The program will use three For Each…Next loops to manipulate the objects each time the user clicks one of the buttons.

Use a For Each…Next loop to change Text properties

  1. Create a new Visual Basic Windows Application project named My Controls Collection.

  2. Use the Button control to draw three button objects on the left side of the form, as shown here:

    graphic

  3. Use the Properties window to set the Name property of the third button object (Button3) to “btnMoveObjects”.

  4. Double-click the first button object (Button1) on the form.

    The Button1_Click event procedure appears in the Code Editor.

  5. Type the following program statements:

    For Each ctrl In Controls     ctrl.Text = "Click Me!" Next

    This For Each…Next loop steps through the Controls collection on the form one control at a time and sets each control's Text property to “Click Me!” The loop uses ctrl as an object variable in the loop, which you'll declare in the following step.

  6. Scroll to the top of the form's program code, and directly below the statement Public Class Form1, type the following comment and variable declaration:

    'Declare a variable of type Control to represent form controls Dim ctrl As Control

    This global variable declaration creates a variable in the Control class type that represents the current form's controls in the program. You're declaring this variable in the general declarations area of the form so that it is valid throughout all of the form's event procedures.

    Now you're ready to run the program and change the Text property for each button on the form.

  7. Click the Start Debugging button on the Standard toolbar to run the program.

  8. Click the first button on the form (Button1).

    The Button1_Click event procedure changes the Text property for each control in the Controls collection. Your form looks like this:

    graphic

  9. Click the Close button on the form.

    The program ends.

    NOTE
    The Text property changes made by the program have not been replicated on the form within the Designer. Changes made at run time do not change the program's core property settings.

  10. Click the Save All button on the Standard toolbar to save your changes. Specify the c:\vb05sbs\chap12 folder as the location.

Now you're ready to try a different experiment with the Controls collection: using the Left property to move each control in the Controls collection to the right.

Use a For Each…Next loop to move controls

  1. Display the form again, and then double-click the second button object (Button2).

  2. Type the following program code in the Button2_Click event procedure:

    For Each ctrl In Controls     ctrl.Left = ctrl.Left + 25 Next

    Each time the user clicks the second button, this For Each…Next loop steps through the objects in the Controls collection one by one and moves them 25 pixels to the right. (To move objects 25 pixels to the left, you would subtract 25 instead.) A pixel is a device-independent measuring unit with which you can precisely place objects on a form.

    TIP
    In Visual Basic 6, you normally use twips instead of pixels to specify measurements.

    As in the previous event procedure you typed, the ctrl variable is a “stand-in” for the current object in the collection and contains the same property settings as the object it represents. In this loop, you adjust the Left property, which determines an object's position relative to the left side of the form.

  3. Click the Start Debugging button.

    The program runs, and three buttons appear on the left side of the form.

  4. Click the second button several times.

    Each time you click the button, the objects on the form gradually move to the right. Your screen looks like this after five clicks:

    graphic

  5. Click the Close button on the form to stop the program.

  6. Click the Save All button to save your changes.

You won't always want to move all the objects on a form as a group. With Visual Basic, you can process collection members individually. In the next exercise, you'll learn how to keep the third button object in one place while the other two buttons move to the right.

Using the Name Property in a For Each…Next Loop

If you want to process one or more members of a collection differently than you process the others, you can use the Name property, which uniquely identifies each object on the form. You've set the Name property periodically in this book to make your program code more readable, but Name also can be used programmatically to identify specific objects in your program.

To use the Name property programmatically, single out the objects to which you want to give special treatment, and then note their Name properties. Then as you loop through the objects on the form by using a For Each…Next loop, you can use one or more If statements to test for the important Name properties and handle those objects differently. For example, let's say you want to construct a For Each…Next loop that moves one object more slowly across the form than the other objects. You could use an If…Then statement to spot the Name property of the slower object and then move that object a shorter distance, by not incrementing its Left property as much as those of the other objects.

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 (btnMove Objects) 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 “Button1” to “btnMoveObjects” in an earlier exercise.

  2. 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.

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

    TIP
    The complete Controls Collection program is located in the c:\vb05sbs\chap12\controls collection folder.

  4. Click the Start Debugging button.

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

  5. Click the third button object six or seven times.

    As you click the button, the top two button objects move across the screen. The third button stays in the same place, however, as shown here:

    graphic

  6. Click the Close button on the form to stop the program.

Giving one object in a collection special treatment can be very useful. In this case, using the Name property in the For Each…Next loop improved the readability of the program code, suggesting numerous potential uses for a game or graphics program. As you use other types of collections in Visual Basic, be sure to keep the Name property in mind.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net