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






3.22/5 (5 votes)
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