简体   繁体   中英

Closing the desired form from a messagebox! (c#)

Here's how my forms are - Form1 is the first form. From Form1 I move to Form2 by using showdialog method (Form1 is in the background and Form2 on top). Now on clicking a button on Form2, a messagebox is shown (mind you, Form1 is still in the background). Messagebox has just the OK button. Now, when I press OK I want to load Form3 and want to close both Form2 and Form1. How can I close Form2 and Form1?? I used this code in Form2:

    private void button1_Click(object sender, EventArgs e)
    {
         if (...)
         {
               MessageBox.Show("hello");
               this.DialogResult = DialogResult.OK;
               this.Close();
               Form3 frm = new Form3();
               frm.ShowDialog();
         }
    }

This method doesn't close Form2 and Form1 but Form3 is showed. So I tried this in Form2:

    private void button1_Click(object sender, EventArgs e)
    {
        if (...)
        {
           if (MessageBox.Show("hello") == DialogResult.OK)
           {
               this.Close();
               Form3 frm = new Form3();
               frm.ShowDialog();
           }
        }
    }  

Still both the forms aren't closed. I tried calling a public close method ( this.Close in Form1 and Form2) created in Form1 and Form2 from Form2 under the MessageBox.Show . Still nothing worked. How to get rid of both forms with message box's OK button??

Thanks. Simple but tricky.. Kindly leave code snippet. I dont understand technical terms unfortunately :-(

You need to know the instances (forms in this case) that you want to close.

In Form2, you could create a variable (eg theOneForm ) to store a reference to Form1 in and set it after creating Form1 (or even in the constructor of Form1).

// in Form2
public Form1 theOneForm {get; set;}

// in Form1
Form2 frm = new Form2();
frm.theOneForm = &this; // correct me if I'm wrong here...

Then from your button1_Click , call theOneForm.Close() - this should close your Form1.

private void button1_Click(object sender, EventArgs e)
{
    if (...)
    {
       if (MessageBox.Show("hello") == DialogResult.OK)
       {
           Form3 frm = new Form3();
           frm.ShowDialog();
           theOneForm.Close();
           this.Close();
       }
    }
} 

Also, close your form after you executed the other code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM