Question

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?

Was it helpful?

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

OTHER TIPS

You need to set the DialogResult in the button click handler on your form. See this SO question

EDIT: And close the form in the handler as well. Missed the forest for the trees.

The setters from the CLR source for System.Windows.Forms.Form.AcceptButton and System.Windows.Forms.Form.CancelButton are below.

Note that the CancelButton setter sets the DialogResult property of the specified button, while the AcceptButton setter doesn't.

At first review this seems to be a bug in the WinForms source code.

Code:

Public Sub set_AcceptButton(ByVal value As IButtonControl)
  If (Not Me.AcceptButton Is value) Then
    MyBase.Properties.SetObject(Form.PropAcceptButton, value)
    Me.UpdateDefaultButton
  End If
End Sub

Public Sub set_CancelButton(ByVal value As IButtonControl)
  MyBase.Properties.SetObject(Form.PropCancelButton, value)
  If ((Not value Is Nothing) AndAlso (value.DialogResult = DialogResult.None)) Then
    value.DialogResult = DialogResult.Cancel
  End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top