tags:

views:

47

answers:

3

Hi,

I have a form in a winforms app. When I press a button, it loads a modal message box with the options yes and no.

This is fine, but when I press no, I want to close both the dialog box and the form where the button which launched the dialog box (the sender) is.

So the app structure is like this:

Main app window > press menu item to launch new form (connection setup) > press button on this form to launch message box.

Two windows are open (connection setup form and dialog box), which I both want closed.

How could I do this?

+8  A: 

In your yes-no modal form, just set DialogResult to No when you press the No button, like:

private void noButton_Click(object sender, EventArgs e)
{
    this.DialogResult = System.Windows.Forms.DialogResult.No;
}

and the modal form will automatically close when you click No

Then when you open your modal form do something like this (in the connection setup form):

var modalForm = new YesNoForm();
if (modalForm.ShowDialog() == DialogResult.No)
{
    this.Close(); // close the connection setup form
}

EDIT

I thought your yes-no modal form was custom, if it's a simple MessageBox, just do:

var dlgResult = MessageBox.Show("Yes or no ?","?",MessageBoxButtons.YesNo);
if(dlgResult == System.Windows.Forms.DialogResult.No)
{
    this.Close(); // close the connection setup form
}

as already suggested in other answers

digEmAll
A: 

I don't know if C# has the same behavior, but in Java I modify the constructor of the message box, and pass a reference to the sender form.

MBox1 = New MBox(ParentForm sender);

Then in the message box you can do:

sender.close(); //or whatever
this.close();

The examples are more "pseudocode-like" but I hope it helps

rlbisbe
+2  A: 

Something like this:

DialogResult result = MessageBox.Show("dialog", "modal", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
      this.Close();
}

For custom modal dialogs code will be similar.

iburlakov