4

I have an asp.net form. In this formI want to clear all the data what I entered in textbox,dropdownlist etc. So how can I do without going to each textbox and set the value.

like TextBox1.Text=""; etc. How can i clear all values of a form ?

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
kbvishnu
  • 14,760
  • 19
  • 71
  • 101

3 Answers3

21

Either

Use this function

private void ClearInputs(ControlCollection ctrls)
{
    foreach (Control ctrl in ctrls)
    {
        if (ctrl is TextBox)
            ((TextBox)ctrl).Text = string.Empty;
        else if (ctrl is DropDownList)
            ((DropDownList)ctrl).ClearSelection();

        ClearInputs(ctrl.Controls);
    }
}

and call it like

ClearInputs(Page.Controls);

or

Redirect to the same page

Response.Redirect(Request.Url.PathAndQuery, true);
naveen
  • 53,448
  • 46
  • 161
  • 251
7

You can use a reset button , on the client side :

<input type="reset" />

Another alternative is to redirect to the current url :

Page.Response.Redirect(Page.Request.Url.RawUrl)

This technique will redirect the user to the current page, as if he just arrived. However, this in only possible if your page is not built with some postback (since the viewstate will be reset).

At least, you can "walk" the entire control tree and clear values of controls of your choice, based for example on the type of the control.

Steve B
  • 36,818
  • 21
  • 101
  • 174
0

You can recurse through the control tree using the Controls property of the page and the child controls. For each control you can then reset it using code like

if (ctl is ITextControl)
    ((ITextControl)ctl).Text = "";

and variations on that theme for checkboxes etc.

MarkXA
  • 4,294
  • 20
  • 22