C#: ShowDialog() keeps returning DialogResult.Cancel

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

private void AddItem()
{
FormAdd dlgAdd = new FormAdd();
DialogResult res = dlgAdd.ShowDialog(this);

if (res != DialogResult.OK)
{
return;
}

// All good to go here
}

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.

private void btnAdd_Click(object sender, EventArgs e)
{
// Do some validation here

this.DialogResult = DialogResult.OK;
}

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