2

Hi i'm doing a simple activity in c# . i want to open a new form2 using a button and the form1 will automatically close when i press that button .Here's My code:

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

Now i don't have idea What method will i use to close automatically the form1. Thank you..

Jay
  • 137
  • 2
  • 5
  • 12

2 Answers2

4

Wont work because the code control will halt on form2.ShowDialog();.

You will have to show form2 in a non-modal fashion:

Form2 form2 = new Form2();
form2.Show();
this.Close(); 

Or I guess you could fake it by hiding the form:

Form2 form2 = new Form2();
this.Visible = false;
form2.Show();
this.Visible = true;

Try both versions to see which is better in your situation. Calling ShowDialog(); will show the form as Modal causing all user mouse/keyboard input to be limited to form2 until you close it.

Edit: The Form2 must be declared as a member variable, it will go out of scope if it is decalred in the button event.

Form2 form2 = new Form2();
private void btnOK_Click(object sender, EventArgs e)
{
this.Visible = false;
form2.Show();
this.Visible = true;
}
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
3

Instead of using this.Close(); use this.Hide() and on formclosing event of Form2 give form1.Show().

for more information go through this link (I asked this question before).

Community
  • 1
  • 1
Mr_Green
  • 40,727
  • 45
  • 159
  • 271