I have a form which will open a new form when one button (form1button) is clicked. And on the child form there will be another button ‘form2button’. Now if I click this form2button the new form2 should be disposed. But because the form2 object is created here in form1 class method, I cannot dispose that object in form2 class method (fom2buttonclick). So I used static to get my work done as in the following psuedo code.
Form1:
class Form1 : Form { static Form2 f2; public void Form1_buttonclick(object sender, EventArgs e) { f2 = new Form2(); } public void Disposef2() { f2.Dispose(); } }
Form2:
class Form2 : Form { public void Form2_buttonclick(object sender, EventArgs e) { Form1 f1 = new Form1(); f1.Disposef2(); } }
Is there any other better way to do it. Or C# design itself doesnot provide an alternative mechanism. I am new to C#.Please help me out..
Edit
I want to close (dispose explicitely) form2 object which is created in form1 class when button on form2 is clicked. This edit is to give some more clarity.
If the two forms doesn’t have a parent-dialog type of relationship, you might just want to hook into the Disposed event on the subform to get notified when it closes.
Then all you have to do in Form2 is simply to close it: