Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent a form to a panel

Tags:

c#

.net

winforms

I have a form with a treeview on one side. Depending on what node is selected, I want to display different content on the right. To keep code and controls manageable, my plan was to isolate content into seperate forms, and display the form inside a panel.

In my TreeView AfterSelect event, I tried instantiating the form, and setting it's Parent to a panel but I get an exception "Top-level control cannot be added to a control.":

Form frmShow = new MyForm();
frmShow.Parent = this.pnlHost;

This is not an MDI configuration, but I tried setting the forms MdiParent property to the parent form, and then setting the form's Parent property to the panel but I get an exception "Form that was specified to be the MdiParent for this form is not an MdiContainer. Parameter name: value":

Form frmShow = new MyForm();
frmShow.MdiParent = this;
frmShow.Parent = this.pnlConfigure;

I can't set the form as an MDI Container because it is not a top level form, it is actually a form that is docked inside a parent form (using the WeifenLuo docking library).

Is there some way to parent a form in a panel in a non MDI framework?

like image 497
Jeremy Avatar asked Dec 19 '10 21:12

Jeremy


1 Answers

Just for the record, this is possible. You can turn a Form into a child control by setting its TopLevel property to false. Like this:

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
        switch (e.Node.Name) {
            case "Node0": embedForm(new Form2()); break;
            // etc..
        }
    }
    private void embedForm(Form frm) {
        // Remove any existing form
        while (panel1.Controls.Count > 0) panel1.Controls[0].Dispose();
        // Embed new one
        frm.TopLevel = false;
        frm.FormBorderStyle = FormBorderStyle.None;
        frm.Dock = DockStyle.Fill;
        frm.Visible = true;
        panel1.Controls.Add(frm);
    }

A user control has less overhead.

like image 94
Hans Passant Avatar answered Sep 18 '22 22:09

Hans Passant