Looping Through Controls In ASP.NET web form

Thursday, January 1, 2004

Looping through all the TextBox controls in an ASP.Net web form is a commonly asked question. A first try at writing such a function is to loop through the Controls property of the web page. Controls are usually nested, however, so you may discover your code doesn’t find all of the textboxes on a page. Some of the objects in the Controls property may be parent containers for additional controls, so you’ll need to keep following the Controls property down the hierarchy to find all of the text box controls.

Here is an example snippet:

 

private void Page_Load(object sender, System.EventArgs e)
{
    LoopTextboxes(Page.Controls);
}

private void LoopTextboxes(ControlCollection controlCollection)
{
    foreach(Control control in controlCollection)
    {
        if(control is TextBox)
        {
            ((TextBox)control).Text = "I am a textbox";
        }

        if(control.Controls != null)
        {
            LoopTextboxes(control.Controls);
        }
    }
}
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!