顶级控件无法添加到控件中

时间:2014-07-18 09:24:04

标签: c# winforms

如何在主要表单中加载面板内的其他表单。

我正在尝试像

这样的东西
private void frmInitialEntryBooks_Load(object sender, EventArgs e)
{
    frmSujbect objForm = new frmSujbect();
    pnl.Controls.Add(objForm);
    objForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    objForm.Dock = DockStyle.Fill;
    objForm.Show();
}

但它会在行Top-level control cannot be added to a control

处抛出异常pnl.Controls.Add(objForm);

3 个答案:

答案 0 :(得分:28)

使用此

private void frmInitialEntryBooks_Load(object sender, EventArgs e)
{
    frmSujbect objForm = new frmSujbect();
    objForm.TopLevel = false;
    pnl.Controls.Add(objForm);
    objForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    objForm.Dock = DockStyle.Fill;
    objForm.Show();
}

您遗失objForm.TopLevel = false;

答案 1 :(得分:3)

在frmsubject中设置TopLevel = False然后尝试

frmSujbect objForm = new frmSujbect();
pnl.Controls.Add(objForm);
objForm.Show();

答案 2 :(得分:1)

我做了以下事情:

方法:

private void PopulateFormIntoTab(Form form)
{
    TabPage page = tabControl1.SelectedTab;
    form.TopLevel = false;
    form.Parent = page;
    form.FormBorderStyle = FormBorderStyle.None;
    form.Dock = DockStyle.Fill;
    form.Show();

    tabControl1.TabPages[tabControl1.SelectedIndex].Controls.Clear();
    tabControl1.TabPages[tabControl1.SelectedIndex].Controls.Add(form);
}

初始化表格:

public Form1()
{
    InitializeComponent();

    tabControl1.TabPages.Clear();
    tabControl1.Dock = DockStyle.Fill;
    tabControl1.TabPages.Add(new TabPage("Form2"));
    tabControl1.TabPages.Add(new TabPage("Form3"));
    tabControl1.TabPages.Add(new TabPage("Form4"));

    PopulateFormIntoTab(new Form2());
}

最后,在选定的标签页上更改索引:

private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    Form form = null;

    switch (tabControl1.SelectedIndex)
    {
        case 1:
            form = new Form3();
            break;
        case 2:
            form = new Form4();
            break;
        default:
            form = new Form2();
            break;
    }

    PopulateFormIntoTab(form);
}