Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two forms ie form1 and form2. Now I have a button on form1. On click of a button i want to close form1 and show form2. The code I have written is like this:
form2 f2=new form2()
f2.show();
this.close()

But this.close closes the entire application.

Could someone please help me?
Thanks in advance.
Posted
Updated 8-May-19 2:05am
v2
Comments
Toli Cuturicu 12-Aug-10 10:21am    
Do not ever again lock a question for editing. It is extremely rude. (to E.F. Nijboer)
E.F. Nijboer 12-Aug-10 10:32am    
When improving the question it gets locked but you still would be able to answer it though. It isn't rude, it's simply to prevent collisions.

If you look in Program.cs, you'll see that Form1 is passed in to Application.Run.

When you close Form1, the framework assumes you're exiting the program.

You can hide Form1, then show Form2, or you can create a background manager and use that in Application.Run to control which form is being used. This will feel a bit hackish unless you find/work out a decent pattern for knowing which forms are open and when you're supposed to close. You will need to create and manage an ApplicationContext that shuts itself down when you have no more forms open. It should also be responsible for creating the forms.

Cheers.
 
Share this answer
 
This is because you defined Form1 as your main form. You could hide it instead (form1.visible = false;) of closing it.

It is possible to close form1 but you have to run the second form to get the messageloop going again, like this:
C#
Application.Run(new form2());


Good luck!
 
Share this answer
 
v3
As form1 is parent and form2 is child form.. so it is not possible to open a child form when a parent form is closed.

SPAM link removed.
 
Share this answer
 
v2
Comments
phil.o 15-Jan-13 3:59am    
Great topic digging !
markovl 15-Jan-13 4:44am    
It was only to post SPAM, so I guess they don't care too much :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900