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.
MSDN docs on disposing of forms:
Dispose will be called automatically if the form is shown using the Show method. If another method such as ShowDialog is used, or the form is never shown at all, you must call Dispose yourself within your application.
Source
On closing vs. disposing:
When a form is closed, all resources created within the object are closed and the form is disposed. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. If the form you are closing is the startup form of your application, your application ends.
The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.
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