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?
Press F5 to build and run the application. Click on the button in the main form to display the sub form. Now, when you press the button in the sub form, the form will be hidden.
On each click, we check if the form's display property is set to none . If the form is already hidden, we show it by setting its display property to block . On the other hand, if the form is not hidden, we hide it by setting its display property to none .
Now go to Solution Explorer and select your project and right-click on it and select a new Windows Forms form and provide the name for it as form2. Now click the submit button and write the code.
Inside Form1, there is a button SwitchFormButton, which has below code: Form2 f2 = new Form2(); f2.
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();
Preserve the instance of Form1
and use it to Show
or Hide
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With