Reputation: 37993
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
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
Reputation: 17808
Add an event handler for the form close event. The EventArgs parameter should have a Cancel property.
Upvotes: 1