Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hello i am a beginner at c#, I have a GUI application with 2 forms and i wanna be able when i close the child that the
parent form will automatically close also?
Thanks.
Posted
Updated 5-Jun-11 2:38am
v2

Have a look at using an Eventhandler for the close event (as described here[^]).
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Jun-11 21:41pm    
Too complex. It's done much simpler. (My 4 for your solution.)
Please see my solution.
--SA
Handle FormClosed[^] event.

In your code, you can do something like this:
C#
LoginForm loginForm = new LoginForm();
loginForm.FormClosed += new FormClosedEventHandler(this.LoginForm_FormClosed);

...

void LoginForm_FormClosed(object sender, FormClosedEventArgs e)
{
  MessageBox.Show("LoginForm has closed, with reason: " + e.CloseReason);
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Jun-11 21:40pm    
It's simpler, simpler. Event is not so good as overriding a method in form is simpler (the form is already derived class, and only for non-main form). My 4.

Please see my solution.
--SA
Kim Togo 6-Jun-11 2:45am    
Thanks SA
Let's approach logically. If there are only two forms, and you want to close both, it means you want to exit the application. Now, one of the forms is a main one; it it defined when Application.Run is called. The form used as an argument becomes main. If you close a main form application exist anyway. You only need to take care about your second form.

Overrides its virtual OnFormClosed method:

C#
//only for non-main form:
protected override void OnFormClosed(FormClosedEventArgs e) {
   Application.Exit();
}


—SA
 
Share this answer
 
Comments
Kim Togo 6-Jun-11 2:46am    
Good answer SA! :-) My 5.
Sergey Alexandrovich Kryukov 6-Jun-11 11:09am    
Thank you, Kim.
--SA
BobJanova 7-Jun-11 7:42am    
Simple and well explained.
Sergey Alexandrovich Kryukov 7-Jun-11 16:40pm    
Thank you, Bob.
--SA
Since Form1 (parent) opens Form2 (child) all you have to to is catch the Form2 Close event in Form1's code. In the event handler you then call Form1.Close().

Cheers!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Jun-11 21:31pm    
What are you talking about? There is no relationship child-parent. This is is owner-owned though.
--SA
Sergey Alexandrovich Kryukov 5-Jun-11 21:41pm    
See my solution. It's simpler.
--SA
Hi,

In the GUI applications when u try to close the child form it will close and parent still opened. but where as in your code if u use application.Exit method it will close both the forms. So check your code

For Better Response please post your sample code.

Thanks & Regards
Sudhakar
 
Share this answer
 

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