在MDI Parent中打开新的子表单时关闭子表单?

时间:2014-03-08 18:14:33

标签: c#

我有一个treeView来打开每个子窗体,但是当我打开新的子窗体时,我仍然可以看到新子窗体后面的前一个子窗体。我想要做的是在打开一个新的子表单时关闭它。 (childForm.Close(); //无法正常工作)

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
    string selectedNodeText = e.Node.Text;
    Form1 myform1 = new Form1();
    Form2 myform2 = new Form2();

    if (selectedNodeText == "1")
    {
        myform1.MdiParent = this;
        myform1.Parent = this.splitContainer1.Panel2;                        
        myform1.Dock = DockStyle.Fill;
        this.splitContainer1.Panel2.Controls.Add(myform1);
        myform1.BringToFront();
        myform1.Show();
    }
    if (selectedNodeText == "2")
    {
        myform2.MdiParent = this;
        myform2.Parent = this.splitContainer1.Panel2;                        
        myform2.Dock = DockStyle.Fill;
        this.splitContainer1.Panel2.Controls.Add(myform2);
        myform2.BringToFront();
        myform2.Show();
    }
}

1 个答案:

答案 0 :(得分:0)

查看表单对象的MdiChildren属性。您可以参考附加到MdiContainer的所有表格。

另一种方法是将表单的引用存储在类本身中,如果打开另一个表单,则关闭旧表单:

private Form1 myform1 = null;
private Form2 myform2 = null;

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
   string selectedNodeText = e.Node.Text;

   if (selectedNodeText == "1" && myform1 == null) {
       myform1 = new Form1()
       // ... some code ...
       if (myform2 != null) {
           myform2.Close();
           myform2 = null;
       }
   }
   if (selectedNodeText == "2" && myform2 == null) {
       myform2 = new Form2()
       // ... some code ...
       if (myform1 != null) {
           myform1.Close();
           myform1 = null;
       }
   }
}