如何在不关闭主窗体c#的情况下从另一个子窗体关闭子窗体
本文关键字:窗体 情况下 另一个 | 更新日期: 2023-09-27 18:25:12
从FORM 1打开FORM 2对话框后,我想通过FORM 2的按钮关闭FORM 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.
}
然后在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.
}
如果您的所有表单都是同一父表单的成员,您只需调用:
var ParentalForm=这个。ParentForm为Foo_MainForm;
确保子表单是表单上的公共/内部成员。
然后:
ParentForm.Foo_FormWantingClosed.Close();
或者只写一行:
(this.ParentForm为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();
}