tags:

views:

43

answers:

2

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?

+2  A: 

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 AccepptButton will be pressed)

digEmAll
+1  A: 

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

asawyer
That'll work, but it's kludgy - requires setting a flag in the click event, which you then read in the closing event. If that's the only way, fine - but I was looking for something a little less workaroundish...
Shaul
It's that or change how your buttons work so that your processing either closes or does not close the form manually, and doesn't rely on the AcceptButton automatic stuff.
asawyer