Search code examples
c#showdialog

Form.ShowDialog OK button doesn't work


In my MainForm I'm declaring a second form:

Form3_addrow testDialog;

I've got a button and method OnClick:

private void button2_Click(object sender, EventArgs e)
{
    ShowMyDialogBox();
}

And ShowMyDialogBox() method:

public void ShowMyDialogBox()
{
    testDialog= new Form3_addrow(tran_in);

    DialogResult dr = testDialog.ShowDialog(this);

    if (dr == DialogResult.Cancel)
    {
        testDialog.Close();
    }
    else if (dr == DialogResult.OK)
    {
        testDialog.Close();
    }
}

When I click the button, testDialog is displayed, but when I click the OK button, testDialog doesn't close... the CANCEL button works though. Why doesn't my form close when I click the OK button?


Solution

  • An alternative to setting the DialogResult in the button click handler would be to set the DialogResult on the OK button itself - in form design you can set the result to OK (this works without needing a click handler at all for the button.)

    It sounds like your cancel button already has this property set