如何将UserControl从另一个窗体添加到MainForm中的面板

时间:2019-01-31 16:14:36

标签: c# winforms

我有2个UserControl呼叫:campain_Post和campain_Interact。

AddCampain form when click AddCampain button in MainForm

如上图所示,我想在AddCampain表单中单击Campain Post按钮时,将Campain_Post UserControl加载到停靠在MainForm中的Panel中,然后关闭该弹出表单。

类似,当单击Campain_Interact按钮时,会将Campain_Interact用户控件加载到停靠在Mainform中的同一面板上,然后关闭该弹出窗体。

但是当我单击Campain Post或Campain Interact时,此行显示错误:pnl.panel2.Controls.Add(camPost)说Onject引用未设置为对象的实例!

现在我的代码是:

AddCampain表单:

private void CampainPost_Click(object sender, EventArgs e)
    {



            ////MainForm pnl = new MainForm();
            MainForm pnl = (MainForm)ParentForm;
            //MainForm pnl = (this.Parent as MainForm);

            Campain_Post camPost = new Campain_Post();
            //pnl.panel2.Controls.Clear();

            pnl.panel2.Controls.Add(camPost);
            camPost.Dock = DockStyle.Fill;
            camPost.BringToFront();

            //MainForm.showUC(new Campain_Post(), pnl.panel2);

    }

    private void CampainInteraction_Click(object sender, EventArgs e)
    {

            //Panel pnl2 = this.Parent as Panel;
            //pnl.panel2.Controls.Clear();
            MainForm pnl = (MainForm)this.ParentForm;
            //MainForm pnl = new MainForm();
            Campain_Interaction camInteract = new Campain_Interaction();

            pnl.panel2.Controls.Add(camInteract);
            camInteract.Dock = DockStyle.Fill;
            camInteract.BringToFront();
    }

包含AddCampain按钮的CampainOverview用户控件:

 private void addCampain_Click(object sender, EventArgs e)
    {
        AddCampain addCampain = new AddCampain();
        addCampain.ShowDialog();

        //UserControl1 user = new UserControl1();
        //user.Show();
    }

0 个答案:

没有答案