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

C# 如何在不关闭主窗体c的情况下从另一个子窗体关闭子窗体#,c#,winforms,C#,Winforms,从表单1打开表单2.0对话框后,我想通过表单2的按钮关闭表单1 表格一 private void btnaddIPrange_Click(object sender, EventArgs e) { new form2().ShowDialog(); } 表格二 private void btnIPRangeCancel_Click(object sender, EventArgs e) { //close FORM 1(I don

从表单1打开表单2.0对话框后,我想通过表单2的按钮关闭表单1

表格一

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

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

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.
}
然后在表格2中:

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.
}   

如果所有表单都是同一父表单的成员,则只需调用:

var ParentalForm=this.ParentForm作为Foo_MainForm

确保子窗体是窗体上的公共/内部成员

然后:

ParentalForm.Foo_formwantingclose.Close()

或者仅在一行中:

(this.ParentForm作为Foo_MainForm.Foo_FormWantingClosed.Close()

从我的头顶上

另一个主意!因为form1是发送方,所以可以将对象强制转换为form1并直接关闭它。例如:

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

我相信你的问题与展示方式有关。如果你简单地调用Show,然后在这个命令之后设置这个。Close,你将打开Form2并关闭Form1。非常感谢,解释得很好,我马上就明白了,尽管我只是一个初学者。谢谢,它成功了。不用担心,很高兴它有帮助!我认为这是一种比其他选择更好(更干净)的方式。