Search code examples
c#controlscode-behind

Clearing all textbox and dropdown controls on a page


I'm trying to clear/reset all textbox and dropdown controls on a page, after a user selects the "Submit" button. I'd like to do it programmatically, so if other controls are added/removed later, it will still work.

I've got this, part of which I borrowed from another similar answer on SO:

protected void ResetAllControls()
{
    foreach (Control c in this.Controls)
    {
        if (c is TextBox)
        {
            TextBox tb = (TextBox)c;
            if (tb != null)
            {
                tb.Text = string.Empty;
            }
        }

        if (c is DropDownList)
        {
            DropDownList ddl = (DropDownList)c;
            ddl.SelectedIndex = -1;
        }
    }
}

c resolves to System.Web.UI.LiteralControl, and never resolves to either Textbox or DropDownList, so it doesn't reset anything on the page. Can someone tell me what I'm missing?


Solution

  • The issue is that the controls of the page are of LiteralControl, HTMLHead, HTMLForm types and the TextBox and DropDownList controls are some controls inside some other controls of the page, not direct children of the page. For example, if you have a form and inside your form you have textboxes and dropdownlists, but they are embedded into the form and the form is embedded into the page, then the DropDownList and TextBox controls you are searching for are not the controls of the page, but controls of a control of your page. So you will need to apply deep-search among your controls. If I am correct in thinking that there are no cycles in controls (I've not been working in WebForms .NET since 2017, so I do not have the freshest memories, to say the least), then something like this should work:

    protected void ResetAllControls(System.Web.UI.ControlCollection currentControls)
    {
        foreach (Control c in currentControls)
        {
            if (c is TextBox)
            {
                TextBox tb = (TextBox)c;
                if (tb != null)
                {
                    tb.Text = string.Empty;
                }
            }
    
            else if (c is DropDownList)
            {
                DropDownList ddl = (DropDownList)c;
                ddl.SelectedIndex = -1;
            }
    
            else
            {
                ResetAllControls(c.Controls);
            }
        }
    }
    

    And you call it initially via ResetAllControls(this.Controls);

    If this runs forever or throws a stackoverflow exception, then there is a cycle among your controls and you will need some further validation instead of just an else for the third case. Let me know if this works out for you.