Reputation: 101
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?
Upvotes: 5
Views: 51226
Reputation: 21
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != "")
{
if (DialogResult.Yes == MessageBox.Show(("Do you want to save changes to Untiteled"), "Notepad", MessageBoxButtons.YesNoCancel))
{
saveFileDialog1.ShowDialog();
FileStream fs = new FileStream(saveFileDialog1.FileName + ".txt", FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(richTextBox1.Text);
sw.Close();
fs.Close();
}
else if (DialogResult.No == MessageBox.Show(("Do you want to save changes to Untiteled"), "Notepad", MessageBoxButtons.YesNoCancel))
{
richTextBox1.Clear();
}
else if (DialogResult.Cancel == MessageBox.Show(("Do you want to save changes to Untiteled"), "Notepad", MessageBoxButtons.YesNoCancel))
{
***//when i click on cancel button...the dialogbox should be close??????????????????????***
}
}
else
{
richTextBox1.Clear();
}
}
Upvotes: 2
Reputation: 57220
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
Upvotes: 20
Reputation: 4232
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.
Upvotes: 4
Reputation: 2090
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
Upvotes: 0