如何在不关闭主窗体的情况下从另一个子窗体关闭子窗体c#

时间:2015-12-01 18:58:44

标签: c# winforms

从FORM 1打开FORM 2.dialog后,我想通过FORM 2中的按钮关闭FORM 1。

表格1

private void btnaddIPrange_Click(object sender, EventArgs e)
{
    new form2().ShowDialog();
}

表格2

private void btnIPRangeCancel_Click(object sender, EventArgs e)
{                        
    //close FORM 1(I don't know the code to close it)
    this.Close();
}   

2 个答案:

答案 0 :(得分:1)

Form2需要对Form1的引用。你可以用几种方法做到这一点。

例如,在Form1中,将新Form2实例的Owner属性设置为this

private void btnaddIPrange_Click(object sender, EventArgs e)
{
    Form2 myForm = new Form2(); // Creates instance of Form2.
    myForm.Owner = this; // Assigns reference to this instance of Form1 to the Owner property of Form2.
    myForm.Show(); // Opens Form2 instance.
    // You can also call myForm.Show(this);
    // instead of the above two lines to automatically assign this form as the owner.
}

然后在Form2中:

private void btnIPRangeCancel_Click(object sender, EventArgs e)
{                        
    if(this.Owner != null) // Check for null.
        this.Owner.Close(); // Closes Form1 instance.
    this.Close(); // Closes current Form2 instance.
}   

答案 1 :(得分:0)

如果您的所有表单都是同一父表单的成员,则只需致电:

var ParentalForm = this.ParentForm as Foo_MainForm;

确保子表单是表单上的公共/内部成员。

然后:

ParentalForm.Foo_FormWantingClosed.Close();

或只是一行:

(this.ParentForm as Foo_MainForm).Foo_FormWantingClosed.Close();

脱离我的头顶。

另一个想法!由于form1是sender,您可以将对象强制转换为form1并直接关闭它。例如:

private void OpenForm2(object sender, EventArgs e)
{                        
    var callingForm = sender as form1;
    if (callingForm != null)
       {
           callingForm.Close();
       }
    this.Close();
}