A question I frequently hear from developers is “How do I loop through the controls on my web page?”
There are a variety of reasons a person may want to loop through the controls on a page; 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 Page 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 on your page. You’d be wrong. A page 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 Page 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 a tree structure.
The following function uses recursion to loop through all the controls on a page and sets the BackColor of all TextBoxes to the specified value.
//C#
private void SetTextBoxBackColor(Control Page, Color clr)
{
foreach (Control ctrl in Page.Controls)
{
if (ctrl is TextBox)
{
((TextBox)(ctrl)).BackColor = clr;
}
else
{
if (ctrl.Controls.Count > 0)
{
SetTextBoxBackColor(ctrl, clr);
}
}
}
}
'VB.NET
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
Else
If ctrl.Controls.Count > 0 Then
SetTextBoxBackColor(ctrl, clr)
End If
End If
Next
The function can be called from pretty much anywhere in your code behind file with a simple line such as this:
SetTextBoxBackColor(Page, Color.Red)
The SetTextBoxBackColor function accepts the Page (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.
Steve Orr is a developer and author and can be found at SteveOrr.net.