Search code examples
c#formspanel

C# open Form in Panel


I have 3 forms. The Mainform, Form2 and Form3.

The Mainform contains a large panel in which Form 2 is displayed when the program is started.

I do that with the following code in my Mainform which works great:

   private Boolean loaded = false;
   private void MainForm_Load(object sender, EventArgs e)
    {
        if (!loaded)
        {
            openChildForm(new Form2());
            loaded = true;
        }
    }

 
    public Form activeForm = null;
    public void openChildForm(Form childForm)
    {
        if (activeForm != null)
        { 
            activeForm.Close();
        }

        activeForm = childForm;
        childForm.TopLevel = false;
        panelMain.Controls.Add(childForm);
        panelMain.Tag = childForm;
        childForm.BringToFront();
        childForm.Show();
    }

Now I want to add a button in Form2 (which is still being displayed in the Panel). When I press that Button, Form2 should remove itself from the Mainform Panel and instead Form3 should be displayed in that MainForm panel. I tried that with the following code in Form2 at Buttonclick:

new Mainform().openChildForm(new Form3());

However, this does not work. It still displays the Form2 in the Panel and doesn't display Panel3. In the Mainform it also says that "activeForm" is "null". I guess it is because of the "new MainForm()" call. Can I just access the MainForm without creating a new Instance?


Solution

  • Now I want to add a button in Form2 (which is still being displayed in the Panel). When I press that Button, Form2 should remove itself from the Mainform Panel and instead Form3 should be displayed in that MainForm panel.

    Can I just access the MainForm without creating a new Instance?

    In Form2, you can cast the ParentForm property to MainForm, and then call openChildForm() against that:

    // ... in Form2 ...
    private void button1_Click(object sender, EventArgs e)
    {
        MainForm mf = this.ParentForm as MainForm;
        if (mf != null)
        {
            mf.openChildForm(new Form3());
        }
    }