Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple and easy way to clear all the input fields in the form.

0.00/5 (No votes)
26 Feb 2010 1  
There are occasions where we have lots of input fields on our webpage. And after submitting the form we are required to reset the form (clear all the fields). As i have already used gridview and i got all the controls from every gridview row using foreach loop by using grvrow.findcontrols(),...
There are occasions where we have lots of input fields on our webpage. And after submitting the form we are required to reset the form (clear all the fields).

As i have already used gridview and i got all the controls from every gridview row using foreach loop by using grvrow.findcontrols(), so there must be some way to find all controls in form also.

Then i have worked for a few hours to find something that will make this easier and with minimum efforts, and i written something like this....


private void btnReset_Click(object sender, System.EventArgs e)
{
Control theForm = Page.FindControl("Form1");
        foreach (Control myControl in myForm.Controls)
        {
            //Clearing text in the TextBox
            if (ctrl is System.Web.UI.WebControls.TextBox)
            {
                (myControl as TextBox).Text = "";
            }
 
           //Clearing Selected RadioButton 
            if (myControl is System.Web.UI.WebControls.RadioButtonList)
            {
                (myControl as RadioButtonList).ClearSelection();
            }
           
 
            //Clearing selected ListBox
            if (myControl is System.Web.UI.WebControls.ListBox)
            {
                (myControl as ListBox).ClearSelection();
            }
 
            //Clearing selected CheckBox
            if (myControl is System.Web.UI.WebControls.CheckBox)
            {
                (myControl as CheckBox).Checked = false;
            }
            //Clearing selected index of DropDown
            if (myControl is System.Web.UI.WebControls.DropDownList)
            {
            //usually dorpdownlists 0 index is used for "- Select -", "- Apply -" etc.  
            (myControl as DropDownList).selectedIndex=0;
            }          
       }
}

I this code only important thing is that use of "as" operator. This operator is used for certain types of conversions between compatible reference types.


after writing this code i suddenly realized that html's reset control serves the same purpose. :-)

But this code also works as good as reset button

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here