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.
<u1:p> </u1:p>
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.)
<u1:p> </u1:p>
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.
<u1:p> </u1:p>
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<u1:p></u1:p>
{
if (ctrl.Controls.Count
> 0)
{
SetTextBoxBackColor(ctrl, clr);
}
}
}
}