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.
Adding a For Each...Next Loop
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.
Try It!
To loop through a collection
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.
In Solution Explorer, select the Form1.vb node in the PlayerTest project, and then from the View menu, choose Designer.
Select the ComboBox control. Then, in the Properties window, select the Items property and click the … button.
In the String Collection Editor, delete the four existing entries, and then click OK.
Double-click the form to open the Code Editor.
Add the following code to the end of the Form_Load event handler (below all the team.Add() statements).
Dim player As Persons.Players For Each player In team ComboBox1.Items.Add(player.Position) Next
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.
Next Steps
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
See Also
Tasks
Using Collections to Manage Multiple Objects
Reference
For Each...Next Statement (Visual Basic)
Other Resources
Programming with Objects: Using Classes
Change History
Date |
History |
Reason |
---|---|---|
April 2009 |
Revised steps in the Try It! section. |
Customer feedback. |