Forms, Controls, and Other Useful Objects - 4.2 Iterating Through All Controls on a Form (Page 2 of 5 )
Problem
You need to make updates to some or all controls on a form at runtime, and all in a common way. You aren’t excited about copying and pasting the same lines over and over again to make the changes to every instance of the same control type.
Solution Sample code folder: Chapter 04\IteratingControls
The form maintains a collection of all controls on the form. Iterate through this collection, and make your changes as you pass by each item.
Iterating Through All Controls on a Form
Discussion
Create a new Windows Forms application, and add three Labelcontrols toForm1. Name the controls whatever you want, and change theirTextproperties to anything you want as well. Next, add twoButton controls to the form, namedActRedandActNormal. Set theirTextproperties toRed andNormal, respectively. Then add the following source code to the form’s code template:
Private Sub ActRed_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ActRed.Click
' ----- Set the background of all labels to red.
UpdateAllLabels(Color.Red)
End Sub
Private Sub ActNormal_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ActNormal.Click
' ----- Set the background of all labels to the
' standard color.
UpdateAllLabels(SystemColors.Control)
End Sub
Private Sub UpdateAllLabels(ByVal withColor As Drawing.Color)
' ----- Scan all controls, looking for labels.
For Each scanControls As Control In Me.Controls
If (TypeOf scanControls Is Label) Then
scanControls.BackColor = withColor
End If
Next scanControls
End Sub
When you run the code and click on each button, the background color of the three labels changes as indicated by the clicked button. Figure 4-2 shows a sample use of this code.

Figure 4-2. All labels set to red
All of a form’s controls appear in a collection accessed through the form’sControlsproperty. Because it is a standard collection, you can iterate through it using theFor Eachstatement, or any other technique that accesses elements of a collection. You can also reference controls by string name:
Dim firstButton = Me.Controls("ActRed")
Although controls of all types are added to theControlscollection, you can still determine their derived data types using theTypeOfstatement, as is done in this recipe’s sample code. This can help you limit updates to a certain type of control in the collection.
See Also Recipes 4.1 and 4.3 also discuss features that are replacements for Visual Basic 6.0 control arrays.
Next: 4.3 Sharing Event-Handler Logic Among Many Controls >>
More Visual Basic.NET Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the Visual Basic 2005 Cookbook, written by Tim Patrick and John Clark Craig (O'Reilly; ISBN: 0596101775). Check it out today at your favorite bookstore. Buy this book now.
|
|