content top
Loop through all controls in a user control

Loop through all controls in a user control

Task :

You have a user control. And you want to loop through all the controls in that user control.
You write the following code

foreach (Control ctrl in control.Controls)
{
//Do your task.
}

And you are wrong. :)

Reason :

As you know, all the forms/Usercontrols have a control collection. A control collection may be a nested collection of controls.
That means a control in a collection (Eg a panel) can contain its child controls(Eg : a label).

So if you loop like this  “foreach (Control ctrl in  control.Controls)” ,
then only the top level controls will be included in the loop.
and you will miss the controls nested inside controls.

Solution : Recursion

Since each controls contain child controls,  recursion is the best method to loop through all the controls.

Following is a method which can  be used to loop through all the controls  and disable all the  Textboxes, Dropdownlists and radio buttons.

/// <summary>
/// This method will loop through the child controls inside the control and disable the controls.
/// </summary>
/// <param name=”control”></param>
private void DisableControls(Control control)
{
foreach (Control ctrl in control.Controls)
{
if (ctrl.GetType().Name == “TextBox”)
{
((TextBox)(ctrl)).Enabled = false;
}
else if (ctrl.GetType().Name == “DropDownList”)
{
((DropDownList)(ctrl)).Enabled = false;

}
else if (ctrl.GetType().Name == “RadioButton”)
{
((RadioButton)(ctrl)).Enabled = false;
}
if (ctrl.Controls.Count > 0)
{
DisableControls(ctrl);
}
}
}

Blog Widget by LinkWithin

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment