开发者

Parent a form to a panel

I have a form with a treeview o开发者_JAVA技巧n 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?


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.


You would be better off creating every panel as a UserControl. These are just like forms, but without the window elements.


and display the form inside a panel

No, don't do that. Use UserControls instead of Forms. Creating/designing a UserControl works just like a Form and it will solve all of your problems (here).


Set frmShow.TopLevel = false if you still want to use a form instead of a UserControl for some reason.


private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    ucAdmin ucA = new ucAdmin(); //ucAdmin is a user control u had created.
    ucA.Visible = true;
    ucA.Dock = DockStyle.Fill;

    this.pnlMain.Controls.Clear(); // pnlMain is the location u are going to display this user control.
    this.pnlMain.Controls.Add(ucA);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜