C # Check before leaving an accept_button event

Sorry if this is a stupid question, but I'm starting here.

I have a simple user dialog with two buttons: Accept and Cancel. The Accept button is an acceptButton form.

I want to do some checks in the Accept_Click event and decide if I can close the dialog or not, but every time it leaves this method, the dialog automatically closes and returns Ok.

What can I do to stop the closing of the dialogue? or should i do something else?

thanks

+6
c # acceptbutton
source share
4 answers

I would have a form level variable (name it _ vetoClosing ). In the accept button, click Event, I would do a check and set a variable based on this:

  private void acceptButton_Click(object sender, EventArgs e) { // Am I valid _vetoClosing = !isValid(); } 

Then in the FormClosing event I would cancel close if _vetoClosing is true

  private void Form_FormClosing(object sender, FormClosingEventArgs e) { // Am I allowed to close if (_vetoClosing) { _vetoClosing = false; e.Cancel = true; } } 

The Turning Accept button is turned off because you are losing the functionality of Enter to Press.

+10
source share

I would check how the controls change, and only activate the "Accept" button if the whole form is valid.

This will allow you to keep the button as the default button (AcceptButton), but to prevent it.

+2
source share

A cleaner solution would be to set DialogResult to None:

 private void acceptButton_Click(object sender, EventArgs e) { if (!isValid()) { this.DialogResult = System.Windows.Forms.DialogResult.None; } } 
+1
source share

Is AcceptButton or CancelButton in the form set by this button? If so, try disabling it and manually setting up DialogResult in your handler when you want to close the dialog box.

0
source share

All Articles