Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, please help
I have a 3 Forms,
Form1 calls Form2 and display it in Form1.Panel1,
Form2 calls Form3 and display it in Form2.Panel1,
when i close Form3 it closes not only Form3 but also Form2.

What I have tried:

i have tried creating eventhandler but it doesn't work on me.
Posted
Updated 19-May-20 2:25am
Comments
Pete O'Hanlon 19-May-20 7:34am    
What code do you use to close Form3?
jRosevla 19-May-20 7:37am    
i use the close button in title bar.
Pete O'Hanlon 19-May-20 7:39am    
I just mocked this up and it works perfectly for me. Perhaps you should share your code as to how you added the forms to each other.
Dave Kreskowiak 19-May-20 9:33am    
You have code, either in Form2 or Form3, that's doing this. Just clicking the close box on Form3 will NOT automatically close Form2 unless you provide some code to do it.

1 solution

In your project, add 3 forms (your naming convention suggests you are using Form1 as the master with Form2 and Form3 as child forms). Add a panel to Form1 and a panel to Form2. Add a button to Form1; this button will be used to add an instance of Form2 into the panel on Form1. In Form2, add a button with a similar purpose; this time aiming to add an instance of Form3 into the panel in Form2. (Note, I have kept the name of the panels to the default of panel1 in both cases).

Now, add the following class to add the forms to the panels.
C#
public static class PanelManager
{
    public static void AddForm<T>(this Panel panel) where T : Form, new()
    {
        T form = new T
        {
            TopLevel = false,
            TopMost = true
        };
        panel.Controls.Add(form);
        form.Show();
    }
}

Form1
In Form1, add a button click event handler and add the following code inside it.
C#
panel1.AddForm<Form2>();
Form2In Form2, add a button click event handler, with the following code:
C#
panel1.AddForm<Form3>();
Run the application and click the button in Form1 - this adds an instance of Form2 inside the panel. Click the button on Form2 to add Form3 into the panel in Form2. Now, click the close button in Form3 and this closes Form3 only.
 
Share this answer
 
Comments
Maciej Los 19-May-20 9:10am    
5ed!
Pete O'Hanlon 19-May-20 9:16am    
Thanks

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