I'm using WinForms. I have 2 forms, Form1 (main form) and Form2 (Child Form). I want to close form1 when the user clicks on the "X" button up at the top of form2. In my code I'm trying to close form1 by saying this.Owner.Close();
but it throws an error. Why is it throwing this error, and how can i close the main form from the child form when the user clicks on the "X" button at the top of the form.
Error
An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll
Form 1
private void btn_Open_Form2_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Owner = this;
frm2.Show();
this.Hide();
}
Form2
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
this.Owner.Close();
}
When you call Close
method of the owner, it raise closing event handler of owned forms and this way the code makes a loop causing stack overflow. You need to correct the code this way:
void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason!= CloseReason.FormOwnerClosing)
this.Owner.Close();
}
If you want to close the application after closing the owned form, you can call Application.Exit
methods:
Application.Exit()
You should remove Form2
from owned forms of it's owner (i.e. Form1). Then you can close Form1
without infinite loop
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
var form1 = Owner;
form1.RemoveOwnedForm(this);
form1.Close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With