-4

how can i dispose the first form when calling second form using c#, Here is my code, :

Form2 f2 = new Form2();
f2.Show();
this.Dispose();
Thomas
  • 1,445
  • 14
  • 30
Waz Wgs
  • 11
  • 2

3 Answers3

1

When you run the command new Form2() you are creating a new Form instance from Form1 as a child element. Therefore, you cannot dispose the parent, Form1 (which is this in your code).

Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • Thanks for this knowledge sir. Now i understand why it's not working – Waz Wgs May 16 '17 at 05:44
  • This is not really true. `f2` is not a child of `this`... The main "problem" here is that `Form1` is the MainForm of the Application: `Application.Run(new Form1());` that's why `Application` (well in fact it's `ApplicationContext`) handles the `HandleDestroyed` event of this instance of `Form1` and calls `ExitThread`which causes the application to shut down. *That means closing/disposing the main form of an application will cause closing the whole application.* – Stephan Bauer May 16 '17 at 12:30
  • Thank you sir stephan for clarification. – Waz Wgs May 17 '17 at 00:54
1

Application will close if you dispose the main form.

Try this code

this.Visible = false;

Form2 f2 = new Form2();

f2.ShowDialog();

this.Visible = true;

This will just hide the main form as long as Form2 is open.

bluekushal
  • 499
  • 6
  • 14
  • Wouldm't this.hide() into making visiblity true for the new form, Then if you need to come back just call another new form? Or would that cause a problem. – Zaid Al Shattle May 16 '17 at 05:45
  • Thank you sir Zaid Al Shattle that's the explanation i wanted to read. First i thought visible and hide has the same effect. I thought this.Hide will create another form but since it was hidden im not going to see that i already created multiple form in background. So now i get it that i should use this.Hide to avoid creating multiple form1 or parent form. Is my understanding is right ? – Waz Wgs May 16 '17 at 05:58
  • Zaid, Hiding the control is equivalent to setting the Visible property to false. Follow [this link](http://stackoverflow.com/questions/3600354/control-difference-between-hide-and-visible) – bluekushal May 16 '17 at 06:13
0

Why you are trying to dispose the main form, Instead You can simply hide the first form:

Form2 f2 = new Form2();

f2.Show();   //It shows the new form(Second Form)

this.Hide(); //It hides the current form

It will hide the Main form and shows the Second form.

User6667769
  • 745
  • 1
  • 7
  • 25