I have a parent form that launches several child forms. Upon closing the child form I need to update several controls on the parent form. I'm guessing that I do this by using an Event of some type, but I'm fairly new to C# and not sure how to accomplish this. Thanks for your help.
How to update the parent form on closing one of it's child forms?
Collapse
X
-
Tags: None
-
You are correct, you can use events here. When you create your child form inside your parent form, simply attach to the child form's FormClosing or FormClosed event. As an example...
Code:ChildForm childForm = new ChildForm(); childForm.FormClosed += new FormClosedEventHandler(childForm_FormClosed); childForm.Show();
Create a delegate on your child form and call it ParentUpdateDel egate (or something like that). Next, create a public property, perhaps called UpdateParent, on the child form that allows access to that delegate and provides get and set functionality. In your form closing or form closed event, whichever you prefer, you can call the delegate with the following code...
Code:if (UpdateParent != null) UpdateParent();
In your main form, when you create the child window, you simply assign the property you created to a method with a matching signature to your delegate. You can name this method anything you like.
As an example, I created a child form object, ChildForm, with an UpdateParentDel egate delegate and an UpdateParent property. I put the call to UpdateParent in the form closed event. In my main form I have a button. This button, when clicked, creates a new instance of ChildForm, assigns its UpdateParent property to a method called UpdateMe, disables the button, then shows the form. In the UpdateMe method, I simply re-enable the button.
The result is when I click the button it opens the child form and disables the button. When the child form closes it will make a call to the delegate, which points to the UpdateMe method on the parent form. The UpdateMe method runs and the button is enabled again.
Both methods work just fine. The advantage of a delegate is that you can send parameters along, which will let you pass data that your parent may need. If you do the event way you can still get the data, it just needs to be available via public properties. In both cases you'll need to make sure you get the data before the child form disposes itself.
I hope that helps you! -
You can do so using Show and Close method of the Form. Let us suppose that
you have 3 forms, Form1 (the main form), Form2 and Form3.
From Form2, if you want to open Form3 and close Form2, you can use the
following code:
Form3 f3 = new Form3();
f3.Show(); // Opens the Form3
this.Close(); // Closes the current form (Form2)
If you close Form1 (which might be the main form), the entire application
will close.
--
Nand Kishore Gupta
"Jason Huang" wrote:Comment
Comment