tags:

views:

49

answers:

2

I have a little application that creates alerts whenever a change to a database is made. I have a few options in the alert form that pops up.
One of the options opens another form (a child form) asking the user for further information.

When the child form gets the necessary information from the user, I want it to close as well as the parent form. So far, I only know how to close the child form, but not the parent form.

Parent form > Opens child form
Child gathers information > User clicks ok in child > child closes, parent closes

^this is what I want

I just don't have the brain power to think about how to communicate across forms to accomplish closing the parent form.

Any help would be much appreciated. Actually, it would be super appreciated. If I could learn how to make my forms communicate with each other, I could really do a lot of damage (in a good way 8D ).

+5  A: 

In the parent form, you can do something like this:

ChildForm f = new ChildForm();
f.FormClosed += (o,e) => this.Close();
f.Show();
BFree
@Justin, I'm getting a delegate() can't take 0 parameters error...
Soo
@BFree, your solution worked perfectly, thanks so much!!! :D
Soo
This doesn't allow the user to cancel whatever they're doing in the child form.
Jamie Ide
^ Good call Jamie, I'll take a look at your solution
Soo
@Soo - I accidentally deleted my original comment. Try `f.FormClosed += delegate { this.Close(); };`
Justin Niessner
Thanks Justin, I can confirm your code works, but I went with Jamie's solution as it checks to make sure the user goes through with the action that closes the form. Have a good weekend!
Soo
+1  A: 

Try this in the parent form:

using (var childForm = new ChildForm())
{
    if (childForm.ShowDialog() == DialogResult.OK)
    {
        Close();
    }
}

Your child form should return a DialogResult by clicking buttons (OK or Cancel) and/or setting the AcceptButton and CancelButton properties in the designer.

Jamie Ide
If the child form is going to be returning much information to the parent form, I prefer to have the child form's class define a static method which creates a child form, performs ShowDialog on it, copies the appropriate information from it into a return data object, destroys the form, and returns the data. In such a scenario, the child form's constructor can be Protected or, if the class won't be inheritable, private.
supercat
I either pass a business object into the child form and let it make changes to the object or, more typically, expose the data as a property on the child form.
Jamie Ide