March 13, 2012

How to Close Parent Form from Child Form in Windows Forms 2.0

With the MSDN forums flooded with similar questions, I decided to dedicate an article for the subject. In this article, we will create two forms, a parent and a child and then open the child form using the Parent Form. When the child form closes, we will close the Parent form too. Let us see how.
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 new 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:
C#
        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();
        }
VB.NET
      Private Sub btnOpenForm_Click(ByVal sender As Object, ByVal
      e As EventArgs)
                  Dim frm2 As Form2 = New Form2()
                  AddHandler frm2.FormClosed, AddressOf
                  frm2_FormClosed
                  frm2.Show()
                  Me.Hide()
      End Sub
      Private Sub frm2_FormClosed(ByVal sender As Object, ByVal e
      As
FormClosedEventArgs)
                  Me.Close()
      End Sub
The trick in this code is to create the FormClosedEventHandler delegate which represents the method that handles a FormClosed event, in our case, for Form2. We then subscribe to this event. So whenever Form2 closes, we close the parent form Form1 too.
That’s it. That was simple. Thanks to a guy called Anderj who shared this idea.
I hope you liked the article and I thank you for viewing it.

No comments:

Post a Comment