6

I have two forms. I need to open a second form with a button. When I open form2 I hide form1. However when I try to show form1 again from form2 with a button it doesn't work. My form1 code is:

Form2 form2 = new Form2();        
form2.ShowDialog();

Inside form2 code:

Form1.ActiveForm.ShowDialog();

or

Form1.ActiveForm.Show();

or

form1.show(); (form1 doesn't exist in the current context)

doesn't work. I do not want to open a new form

Form1 form1 = new Form1();   
form1.ShowDialog();

I want show the form which I hided before. Alternatively I can minimize it to taskbar

this.WindowState = FormWindowState.Minimized;

and maximize it from form2 again.

Form2.ActiveForm.WindowState = FormWindowState.Maximized;

however the way I am trying is again doesn't work. What is wrong with these ways?

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Oktay
  • 127
  • 1
  • 2
  • 15

5 Answers5

8

You could try (on Form1 button click)

Hide();
Form2 form2 = new Form2();        
form2.ShowDialog();
form2 = null;
Show();

or (it should work)

Hide();
using (Form2 form2 = new Form2())       
    form2.ShowDialog();
Show();
Marco
  • 56,740
  • 14
  • 129
  • 152
2

Preserve the instance of Form1 and use it to Show or Hide.

Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
1

You can access Form1 from Form2 throught the Owner property if you show form2 like this:

form2.ShowDialog( form1 )

or like this:

 form2.Show( form1 )

Notice this way you are not forced to use ShowDialog cause hide and show logic can be moved inside Form2

Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50
1

This method is the one that I find works the best for me

Primary Form

Form2 form2 = new Form2(this);

Secondary Form

private Form Form1
public Form2(Form Form1)
{
    InitializeComponent();
    this.Form1 = Form1;
    Form1.Hide();
}

Later on when closing

private void btnClose_Click(object sender, EventArgs e)
{
    Form1.Show();
    this.Close();
}
user3569147
  • 104
  • 3
  • 9
0
      FormCollection frm = Application.OpenForms;

        foreach(Form f in frm)
        {
            if(f.Name=="yourformname")
            {
                f.Show();
                this.Close();                    
                this.Dispose();
                return;
            }
        }
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 29 '22 at 10:23