C #: How to undo the close action for the button set as the “Accept” or “Cancel” button in the form?

I have a button btnOKin my form with a property DialogResult OK. The form property is AcceptButtonassigned a value btnOK. Therefore, if I click the button, the form closes automatically.

Now, inside the method btnOK_Click(), I want to be able to undo the closing action, for example. if there was an error, I want to show the message box and not close the form.

How should I do it?

+5
source share
3 answers

IMO you just do not need to set the property DialogResulton the button, but set it directly in your form in the event btnOK_Click:

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 ENTER ( , AcceptButton)

+6

:

this.DialogResult = DialogResult.None
+8

Add an event handler for the form closing event. The EventArgs parameter must have a Cancel property.

+1
source

All Articles