5

The problem is this:

I have a form that accepts a TextBox text and 2 buttons, one to save the text into the database and the other one to cancel and close the form. The form also has an ErrorProvider that's used in the TextBox.Validating event like this:

private void txtNombre_Validating(object sender, CancelEventArgs e)
{
    string errorMsg;
    if (!ValidateText(txtNombre.Text, out errorMsg))
    {
        // Cancel the event and select the text to be corrected by the user.
        e.Cancel = true;
        txtNombre.Select(0, txtNombre.Text.Length);

        // Set the ErrorProvider error with the text to display.  
        this.errorProvider1.SetError(txtNombre, errorMsg);
    }
}

It does what is expected, to not let the user to do anything in the form until the required field is filled, except for 1 thing: to let the user close the form via the Cancel button. I tried comparing the object sender to the button cmdCancel but it's not possible because the sender is always the TextBox.

Any advice as to how to ignore the Validating event when the user clicks on cmdCancel?

  • 1
    This question is duplicate http://stackoverflow.com/questions/1882523/how-to-skip-validating-after-clicking-on-a-forms-cancel-button. Try setting cmdCancel.CausesValidation = false; http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.causesvalidation.aspx – Mihai Hantea Mar 06 '14 at 01:00

2 Answers2

3

Look at the property Control.CausesValidation. Set it to false for your cancel button.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
2

Set CausesValidation to false on the Cancel button.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272