Shaul Behr
Shaul Behr

Reputation: 37993

C#: How to cancel the close action for a button that's set as the Accept or Cancel button on a form?

I have a button btnOK on my form, with a DialogResult property of OK. The form's AcceptButton property is set to btnOK. So if I click the button, the form closes automatically.

Now, inside the btnOK_Click() method, I want to ability to cancel out of the close action, e.g. if there was an error I want to show a message box and not close the form.

How do I do it?

Upvotes: 7

Views: 5093

Answers (3)

digEmAll
digEmAll

Reputation: 57210

IMO you just don't have to set DialogResult property on the button, but set it directly on your form in the btnOK_Click event:

private void btnOK_Click(object sender, EventArgs e)
{
    if (yeahLetsClose)
        this.DialogResult = DialogResult.OK;  // form will close with OK result
    // else --> form won't close...
}

BTW, AcceptButton property is related to ENTER key (when you press it on your form, the AcceptButton will be pressed)

Upvotes: 6

Radek
Radek

Reputation: 141

On error add:

this.DialogResult = DialogResult.None

Upvotes: 14

asawyer
asawyer

Reputation: 17808

Add an event handler for the form close event. The EventArgs parameter should have a Cancel property.

Upvotes: 1

Related Questions