tags:

views:

77

answers:

4

I am working in c# windows application.I have two windows from name as form1 and form2.i am calling form2 by clicking the button in form1 but i create the object for form2 in constrcutor of form1 .if i click the button first time form2 showed successfully after that i close the form2 by clicking the default close button and again click the button now i am getting object disposed exception was unhandled exception.how can avoid this?

+1  A: 

You are keeping a reference to the object (window here) but you are closing it. Object is disposed but is not garbage collected. Your reference here is invalid now as the object has lost its usable state.

You need to hide the form instead of close if you need to re-use it. Or create a new instance to load it again.

Aliostad
+1  A: 

You can use events in order to let form1 know when form2 has been closed and clear its reference to it. Then form1 doesn't need to call form2 if it has been closed.

Felix Ungman
Yep. The best way. form2 reference must be set to null when Form_closed event fires
ILya
A: 

We do something similar here with a few of our tools that plug into third-party apps. Code sample below:

public class Form1 : Form
{
    private Form2 otherForm;

    private void ActivateForm2_Click(object sender, EventArgs e)
    {
        if (otherForm == null || otherForm.IsDisposed)
        {
            otherForm = new Form2();
            otherForm.FormClosed += new FormClosedEventHandler(otherForm_closed);
        }
        otherForm.Show(this);
    }

    private void otherForm_Closed(object sender, FormClosedEventArgs e)
    {
        otherForm.Dispose();
        otherForm = null;
    }
}
StyxRiver
+1  A: 

Don't handle the exception, fix the bug in your code. The form instance is dead after the form is closed, you cannot show it again. Either write it like this:

    private void button1_Click(object sender, EventArgs e) {
        var frm = new Form2();
        frm.Show(this);
    }

Or if you want only one instance of the form to be ever visible:

    Form2 theForm;

    private void button1_Click(object sender, EventArgs e) {
        if (theForm != null) {
            theForm.WindowState = FormWindowState.Normal;
            theForm.BringToFront();
        }
        else {
            theForm = new Form2();
            theForm.FormClosed += delegate { theForm = null; };
            theForm.Show(this);
        }
    }
Hans Passant