Recipe 4.2. Iterating Through All Controls on a Form


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.

Discussion

Create a new Windows Forms application, and add three Label controls to Form1. Name the controls whatever you want, and change their Text properties to anything you want as well. Next, add two Button controls to the form, named ActRed and ActNormal. Set their Text properties to Red and Normal, 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's Controls property. Because it is a standard collection, you can iterate through it using the For Each statement, 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 the Controls collection, you can still determine their derived data types using the TypeOf statement, 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.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

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