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

C#.NetWindowsWinforms

C# Problem Overview


I have a dialog that I show with <class>.ShowDialog(). It has an OK button and a Cancel button; the OK button also has an event handler.

I want to do some input validation in the event handler and, if it fails, notify the user with a message box and prevent the dialog from closing. I don't know how to do the last part (preventing the close).

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

You can catch FormClosing an there force the form to remain opened. use the Cancel property of the event argument object for that.

e.Cancel = true;

and it should stop your form from closing.

Solution 5 - C#

This doesn't directly answer your question (other already have), but from a usability point of view, I would prefer the offending button be disabled while the input is not valid.

Solution 6 - C#

Use this code:

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

The problem of it is that the user has to clic two times the buttons for closing the forms;

Solution 7 - C#

Just add one line in the event function

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
			 {
				this->DialogResult = System::Windows::Forms::DialogResult::None;
			 }

Solution 8 - C#

I wish I had time to find a better example, but you would be much better off using the existing windows forms validation techniques to do this.

http://msdn.microsoft.com/en-us/library/ms229603.aspx

Solution 9 - C#

void SaveInfo()
{
blnCanCloseForm = false;
Vosol[] vs = getAdd2DBVosol();
if (DGError.RowCount > 0)
return;

Thread myThread = new Thread(() =>
{
this.Invoke((MethodInvoker)delegate {
	picLoad.Visible = true;
	lblProcces.Text = "Saving ...";
});
int intError = setAdd2DBVsosol(vs);
Action action = (() =>
{
	if (intError > 0)
	{
		objVosolError = objVosolError.Where(c => c != null).ToArray();
		DGError.DataSource = objVosolError;// dtErrorDup.DefaultView;
		DGError.Refresh();
		DGError.Show();
		lblMSG.Text = "Check Errors...";
	}
	else
	{
		MessageBox.Show("Saved All Records...");
		blnCanCloseForm = true;
		this.DialogResult = DialogResult.OK;
		this.Close();
	}

});
this.Invoke((MethodInvoker)delegate {
	picLoad.Visible = false;
	lblProcces.Text = "";
});
this.BeginInvoke(action);
});
myThread.Start();
}

void frmExcellImportInfo_FormClosing(object s, FormClosingEventArgs e)
{
	if (!blnCanCloseForm)
		e.Cancel = true;
}

Solution 10 - C#

You can probably check the form before the users hits the OK button. If that's not an option, then open a message box saying something is wrong and re-open the form with the previous state.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionqsterView Question on Stackoverflow
Solution 1 - C#ArjanView Answer on Stackoverflow
Solution 2 - C#ChrisFView Answer on Stackoverflow
Solution 3 - C#Hans PassantView Answer on Stackoverflow
Solution 4 - C#Adrian FâciuView Answer on Stackoverflow
Solution 5 - C#BenjolView Answer on Stackoverflow
Solution 6 - C#cigos emmanuelView Answer on Stackoverflow
Solution 7 - C#CrokoView Answer on Stackoverflow
Solution 8 - C#MeshView Answer on Stackoverflow
Solution 9 - C#Ata HoseiniView Answer on Stackoverflow
Solution 10 - C#Icono123View Answer on Stackoverflow