Preventing a dialog from closing in the button's click event handler Preventing a dialog from closing in the button's click event handler windows windows

Preventing a dialog from closing in the button's click event handler


You can cancel closing by setting the Form's DialogResult to DialogResult.None.

An example where button1 is the AcceptButton:

private void button1_Click(object sender, EventArgs e) {  if (!validate())     this.DialogResult = DialogResult.None;}

When the user clicks button1 and the validate method returns false, the form will not be closed.


Given that you've specified you want a pop error dialog, one way of doing this is to move your validation into a OnClosing event handler. In this example the form close is a aborted if the user answers yes to the question in the dialog.

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e){   // Determine if text has changed in the textbox by comparing to original text.   if (textBox1.Text != strMyOriginalText)   {      // Display a MsgBox asking the user to save changes or abort.      if(MessageBox.Show("Do you want to save changes to your text?", "My Application",         MessageBoxButtons.YesNo) ==  DialogResult.Yes)      {         // Cancel the Closing event from closing the form.         e.Cancel = true;         // Call method to save file...      }   }}

By setting e.Cancel = true you will prevent the form from closing.

However, it would be a better design/user experience to display the validation errors inline (via highlighting the offending fields in some way, displaying tooltips, etc.) and prevent the user from selecting the OK button in the first place.


Don't use the FormClosing event for this, you'll want to allow the user to dismiss the dialog with either Cancel or clicking the X. Simply implement the OK button's Click event handler and don't close until you are happy:

private void btnOk_Click(object sender, EventArgs e) {  if (ValidateControls())    this.DialogResult = DialogResult.OK;}

Where "ValidateControls" is your validation logic. Return false if there's something wrong.