Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

c# - Parent a form to a panel

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...