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

I was going to suggest a solution similar to Task's except (as sixlettervariables points out) we need to implement it as 1 extension method and essentailly switch on the precise type of the control passed in (i.e. copy your logic that you posted in your question).

public static class ControlExtensions
{
    public static void Clear( this Control c )
    {
        if(c == null) {
            throw new ArgumentNullException("c");
        }
        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....
    }
}

It is not particularly elegent looking method but your code in your page/control is now the more succinct

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

and you can of course now call control.Clear() anywhere else in you code.


You can do

foreach (Control c in myUserControl.Controls) {
    myUserControl.Controls.Remove(c);
}

Because Controls is just a list, you can call Remove() on it, passing it what you want to remove.

EDIT: Oh I'm sorry, I didn't read it correctly. I don't know of a way to do this, maybe someone here who is good with Reflection could make it where you could do like

foreach (Control c in myUserControl.Controls) {
    c = new c.Type.GetConstructor().Invoke();
}

or something, to turn it into a freshly made component.