在C#中,当我单击第二个表单的按钮时,如何在第一个表单中打开第三个表单

时间:2019-03-14 12:27:21

标签: c# .net visual-studio winforms

在我的Windows Forms应用程序中,我有3个不同的Form Form1,Form2,Form3

  • Form1 包含一个按钮和一个面板(button1,panel1)

    Form1 Image

  • Form2 仅包含一个按钮(按钮)

    Form2 Image

  • Form3 不包含任何内容

    Form3 Image

在Form1中,当我单击button1时,Form2在panel1 (see in image)

中打开
private void button1_Click(object sender, EventArgs e)
{
    panel1.Controls.Clear();
    Form2 f2 = new Form2();
    f2.TopLevel = false;
    panel1.Controls.Add(f2);
    f2.Dock = DockStyle.Fill;
    f2.Show();
}

现在,在Form2中,当我单击按钮时,我想在Form1的面板中打开Form3,我已经尝试过此代码...

Form1 f1 = new Form1();
private void button1_Click(object sender, EventArgs e)
{
    f1.panel1.Controls.Clear();
    Form3 f3 = new Form3();
    f3.TopLevel = false;
    f1.panel1.Controls.Add(f3);
    f3.Dock = DockStyle.Fill;
    f3.Show();
}

注意:在Form1中,我已将面板的修改器更改为public

1 个答案:

答案 0 :(得分:0)

步骤1:在Form1中创建函数以显示其他表单:

class Form1
{
    public void ShowForm2() {...}
    public void ShowForm3() {...}
    // TODO: think about: do you need IsForm2Shown?
    // TODO: think about what you want if ShowForm2 is called twice
    ...

}

步骤2:让Form2知道Form1。给Form2一个函数以在Form1内显示Form3

class Form2
{
    public Form1 Form1 {get; set;}

    protected void ShowForm3InsideForm1()
    {
        this.Form1.ShowForm3();
    }
}

每当表单1创建Form2时,都应填充属性Form1。因此,在Form1.ShowForm2()中:

var form2 = new Form2()
{
   Form1 = this,
   ...
}
form2.Show();

第3步:每当在Form 2中找到要“在Form 1中显示Form 3”时,只需调用适当的函数

// Somewhere inside Form2 code you decide that you want to show Form3 inside Form1:
this.ShowForm3InsideForm1();

简单的漫画卓悦!