1

i am validating my text box through the validating and validated events , below is my code

    private void tbms_Validating(object sender, CancelEventArgs e)
    {
        if (tbms.Text.Length==0)
        {
            MessageBox.Show("Ms is Empty");
            e.Cancel = true;
        }
    }

    private void tbms_Validated(object sender, EventArgs e)
    {
        MessageBox.Show("No Error");
    }

Its works nice , but the problem i am facing is if there is no text in text box and i want to close the application through the cancel button on control box its show me the message box that Ms is Empty and prompt me again to the window . when i put some text in text box and i click the cancel button the application closed. Kindly give hint how to solve this problem.Thanks in advance. Regards

  • Duplicate: http://stackoverflow.com/questions/1882523/how-to-skip-validating-after-clicking-on-a-forms-cancel-button – RJ Lohan Nov 05 '13 at 20:34
  • @RJ Lohan , i can do it using an extra button by naming it cancel button and setting the cause validation to false, or auto validate to disable etc etc , but i do not want to use a extra button to close the app, i only want to use the cancel button on the control box. Thanks – Mati Rehman Nov 05 '13 at 20:43

3 Answers3

1

Validation will also occur when your form is being closed. If your Validating event sets the e.Cancel property to true then the default FormClosing event will stop the form from closing. You can work around this like this:

private void CancelButton_Click(object sender, EventArgs e) {
    this.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
    this.Close();    // or this.DialogResult = DialogResult.Cancel
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1
  1. Set property KeyPreview to True in your Form.
  2. Add a button and write the ESC code (Ex. Me.Dispose())
  3. In your Form, select your button from the "CancelButton Property List".
  4. The button always must be Visible = True to work. If you don't want to show it, put the button behind any other object or localize it at top = -100 and left = -1, for example. But the button always must be Visible = true
boop_the_snoot
  • 3,209
  • 4
  • 33
  • 44
0

You need to set the "CausesValidation" property to false on the cancel button

Michael
  • 484
  • 6
  • 8