There are a variety of reasons a person may want to loop through the controls on a Form; perhaps to set a common color or to validate custom business rules. This kind of thing is not hard to do, but the logic is not entirely intuitive unless you know a few details.
You might already know that every Form has a Controls collection. From that, you might assume that you can simply loop through this collection to do what you need to all the controls in your form. You’d be wrong. A form is a complex tree of controls, and many controls can contain collections of controls themselves, such as a Panel and a Table. In fact, a form itself is nothing more than a fancy Control. (It inherits from, and extends the Control class.)
Since each tree branch can itself have N child branches, the only efficient solution is recursion. A recursive function is a function that calls itself as many times as necessary to work through any kind of hierarchical structure.
private void SetTextBoxBackColor(Control Page, Color clr)
foreach (Control ctrl in Page.Controls)
if (ctrl is TextBox)
((TextBox)(ctrl)).BackColor = clr;
if (ctrl.Controls.Count > 0)
Private Sub SetTextBoxBackColor(ByVal Page As Control, _
ByVal clr As Color)
For Each ctrl As Control In Page.Controls
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).BackColor = clr
If ctrl.Controls.Count > 0 Then
Figure 1: This code loops recursively through all the controls in Form to set the backcolor of all the TextBoxes to a common color.
The function in Figure 1 can be called from pretty much anywhere in your code behind file (or Windows Form class) with a simple line such as this:
SetTextBoxBackColor(Me, Color.Red) 'VB.NET
- or -
SetTextBoxBackColor(this, Color.Red); //C#
The SetTextBoxBackColor function accepts the Form (or any other container control) as a parameter, along with the color that will be applied to the background of each TextBox within. The ForEach loop iterates through each control in the collection. If the Control is a TextBox, it applies the BackColor. If the control contains other controls, the function calls itself recursively to loop through each of those controls, and so on.
You can take these same principals and modify them in many ways as a potential solution for virtually anything you’d want to do to all your controls or to a certain kind of control. You now have the secrets you need to tinker with an entire control tree using recursion.