Clear all fields in ASP.net form

Is there an easy way to reset all the fields in a form?

I have around 100 controls in my asp.net form and there are submit and reset buttons.

How do I make all values in the fields null when user hits reset button?

I have a lot of dropdown boxes, textboxes, checkboxes.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Add this to the server-side handler of the cancel button:

Response.Redirect("~/mypage.aspx", false);

Method 2

Loop through all of the controls on the page, and if the control is type TextBox, set the Text property to String.Empty

protected void ClearTextBoxes(Control p1)
{
    foreach (Control ctrl in p1.Controls)
    {
        if(ctrl is TextBox)
        {
             TextBox t = ctrl as TextBox;

             if(t != null)
             {
                  t.Text = String.Empty;
             }
        }
        else
       {
           if (ctrl.Controls.Count > 0)
           {
               ClearTextBoxes(ctrl);
           }
        }
    }
}

Then to call it in your click event like this:
 ClearTextBoxes(Page);

Method 3

Try adding an:

<input type="reset" value="Clear" />

to your form.

Method 4

You can make use of OnClientClick event. This will reset all all the control present on the form. OnClientClick="this.form.reset();return false;"

See the Code :

<asp:Button ID="Reset_Button" runat="server" Text="Reset" 
    Width="81px" OnClientClick="this.form.reset();return false;" />

Method 5

The best option from my side would be

Response.Redirect(Request.RawUrl);

Just add this code on the cancel or reset button of your asp.net control.

Method 6

If you are using asp.net formview object, just use myFormView.DataBind(); in your reset button click event.

Method 7

Or if you are using Angular.

Add this to your button on the cshtml page:

<input type="button" value="Cancel" id="cancel" ng-click="cancel();" />

And this to your .js file:
$scope.cancel = function () {
    if (!$('form').dirtyForms('isDirty')) {
        $('form').dirtyForms('setClean');
    }
    else {
        $('form').dirtyForms('isDirty', true);
    }
     var that = this;
    var method = that.getUrl('CONTROLLER', 'ACTION', 'id', 'querystring');
    window.location = method;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x