Closer Look: Using a For Each...Next Loop in a Collection

In this lesson, you will learn to use a For Each...Next loop to loop through a collection.

In an earlier lesson, you learned to use a For...Next loop to execute a block of code a specified number of times. The Visual Basic collection objects support a special type of loop, the For Each...Next loop, which you can use to execute a block of code for each element in the collection instead of executing the block a set number of times.

In the previous lesson, you manually added the values for the Position property of the Players objects in the team collection to the ComboBox control. While this worked for the example, it is not the best practice—each time you added a new player, you would also have to update the Items collection of the ComboBox control.

A better way to handle this would be to add the Position values to the Items collection by looping through the team collection using a For Each...Next loop.

In a For...Next loop, you must first declare a counter variable; with a For Each...Next loop, you must first declare an object variable. The following code demonstrates a For Each...Next loop.


Dim player As Persons.Players
For Each player In team
    ComboBox1.Items.Add(player.Position)
Next


In this case, no matter how many Players you have, the ComboBox1.Items.Add method is executed once for each Players object in the team collection, and the Position value is added to the list.

To loop through a collection

  1. Open the Persons project from the previous lesson. If you did not finish it, go back to the previous lesson, Using Collections to Manage Multiple Objects, and complete the procedures.

  2. In Solution Explorer, select the Form1.vb node in the PlayerTest project, and then from the View menu, choose Designer.

  3. Select the ComboBox control. Then, in the Properties window, select the Items property and click the button.

  4. In the String Collection Editor, delete the four existing entries, and then click OK.

  5. Double-click the form to open the Code Editor.

  6. In the Code Editor, add the following to the declarations section (below the declaration for team).

    
    Dim player As Persons.Players
    For Each player In team
        ComboBox1.Items.Add(player.Position)
    Next
    
    
    
  7. Press F5 to run the program. Select a position from the drop-down list. The player for that position is displayed in a message box.

In this lesson, you used a For Each...Next loop in a collection. In the following lessons, you will create another type of object—a user control.

Next Lesson: Visible Objects: Creating Your First User Control

Show: