I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?
When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.
The Form class doesn't provide any kind of reference to the 'parent' Form, so there's no direct way to access the parent (unless it happens to be the MDI parent as well, in which case you could access it through the MDIParent property). You'd have to pass a reference to the parent in the constructor of the child, or a property and then remember to set it, and then use that reference to force the parent to close.
Not sure what you mean by "child form". Perhaps it's a button on a panel on a form? Or is it a MDI thing? Or is the child form a dialog box?
Perhaps consider having the parent subscribe to an event on the child, and the child can fire that event whenever it wants to close the parent. The parent can then handle it's own closing (along with the child's).
You are clearly noo using the correct way to open and close forms. If you use any form of MVC or MVP this problem would not arise.
So use a form of MVP or MVC to solve this problem.
I agree with davidg; you can add a reference to the parent form to the child form's constructor, and then close the parent form as you need:
private Form pForm;
public ChildForm(ref Form parentForm)
{
pForm = parentForm;
}
private closeParent()
{
if (this.pForm != null)
this.pForm.Close();
this.pForm = null;
}
I ran across this blog entry that looks like it will work and it uses the Event Handler concept from D2VIANT Answer
http://www.dotnetcurry.com/ShowArticle.aspx?ID=125
Summary: Step 1: Create a new Windows application. Open Visual Studio 2005 or 2008. Go to File > New > Project > Choose Visual Basic or Visual C# in the ‘Project Types’ > Windows Application. Give the project a name and location > OK.
Step 2: Add a n ew form to the project. Right click the project > Add > Windows Forms > Form2.cs > Add.
Step 3: Now in the Form1, drag and drop a button ‘btnOpenForm’ and double click it to generate an event handler. Write the following code in it. Also add the frm2_FormClosed event handler as shown below:
private void btnOpenForm_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
frm2.Show();
this.Hide();
}
private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}