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)
{
if (ctrl is System.Web.UI.WebControls.TextBox)
{
(myControl as TextBox).Text = "";
}
if (myControl is System.Web.UI.WebControls.RadioButtonList)
{
(myControl as RadioButtonList).ClearSelection();
}
if (myControl is System.Web.UI.WebControls.ListBox)
{
(myControl as ListBox).ClearSelection();
}
if (myControl is System.Web.UI.WebControls.CheckBox)
{
(myControl as CheckBox).Checked = false;
}
if (myControl is System.Web.UI.WebControls.DropDownList)
{
(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