asp.netaspbutton

Why is the Button in this case validating the TextBoxes?


It looks very simple, but becoming increasingly frustrating. I am working with a ASP.NET WebForm where I have the following code for ButtonClear that clears the text that is entered in the TextBoxes:

protected void ButtonClearAll_Click(object sender, EventArgs e)
{
    TextBox1.Text = string.Empty;
    TextBox2.Text = string.Empty;
    TextBox3.Text = string.Empty;
    TextBox4.Text = string.Empty;
}

Code in .aspx file:

<asp:Button ID="ButtonClearAll" runat="server" Text="Clear" OnClick="ButtonClearAll_Click"/>

Problem: By clicking ButtonClearAll once, the four TextBoxes are clearing fine. But on subsequent click, the RequiredFieldValidators of the 4 TextBoxes are getting called and are validating the assigned TextBoxes to print the appropriate error statements next to each TextBox.

What to do?


Solution

  • By default any button, invoking any post-back, is going to invoke the validation first. You can disable validation for a particular button with the CausesValidation property:

    <asp:Button ID="ButtonClearAll" CausesValidation="false" ... />