C#: ShowDialog() keeps returning DialogResult.Cancel

0 Comments

When you call a dialog with dlg.ShowDialog() and check the result, you may find it always returning DialogResult.Cancel.

01.private void AddItem()
02.{
03.  FormAdd dlgAdd = new FormAdd();
04.  DialogResult res = dlgAdd.ShowDialog(this);
05. 
06.  if (res != DialogResult.OK)
07.  {
08.    return;
09.  }
10. 
11.  // All good to go here
12.}

So with your dialog, ensure that the correct "AcceptButton" property has been set to the correct button.

A simple mistake to make is to forget setting the result when you click OK/Save/etc.

1.private void btnAdd_Click(object sender, EventArgs e)
2.{
3.  // Do some validation here
4. 
5.  this.DialogResult = DialogResult.OK;
6.}

That should set the correct value by the time the dialog is closed.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog