# How do I loop through all the controls in a form?

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. The following function uses recursion to loop through all the controls in a Form and sets the BackColor of all TextBoxes to the specified value. The function works with both Web Forms and Windows Forms.

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);

}

}

}

}

The function in can be called from pretty much anywhere in your code behind file
(or Windows Form class) with a simple line such as this:

SetTextBoxBackColor(this, Color.Red); //C#
Reactions