How can I dynamically clear all controls in a user control?

Posted by Michael on Stack Overflow See other posts from Stack Overflow or by Michael
Published on 2010-05-19T18:25:46Z Indexed on 2010/05/19 18:30 UTC
Read the original article Hit count: 296

Filed under:
|
|
|
|

Is it possible to dynamically (and generically) clear the state of all of a user control's child controls? (e.g., all of its TextBoxes, DropDrownLists, RadioButtons, DataGrids, Repeaters, etc -- basically anything that has ViewState)

I'm trying to avoid doing something like this:

foreach (Control c in myUserControl.Controls)
{
    if (c is TextBox)
    {
        TextBox tb = (TextBox)c;
        tb.Text = "";
    }
    else if (c is DropDownList)
    {
        DropDownList ddl = (DropDownList)c;
        ddl.SelectedIndex = -1;
    }
    else if (c is DataGrid)
    {
        DataGrid dg = (DataGrid)c;
        dg.Controls.Clear();
    }

    // etc.

}

I'm looking for something like this:

foreach (Control c in myUserControl.Controls)
    c.Clear();

...but obviously that doesn't exist. Is there any easy way to accomplish this dynamically/generically?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about usercontrols