Mati Rehman
Mati Rehman

Reputation: 25

Close button not working in windows forms application

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

Upvotes: 1

Views: 2737

Answers (3)

Arnaldo Benitez
Arnaldo Benitez

Reputation: 11

  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

Upvotes: 1

Michael
Michael

Reputation: 854

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

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941257

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
}

Upvotes: 1

Related Questions