开发者

How to handle object disposed exception was unhandled Exception in c#?

开发者 https://www.devze.com 2023-01-16 00:48 出处:网络
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 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 butt开发者_运维百科on now i am getting object disposed exception was unhandled exception.how can avoid this?


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);
        }
    }


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.


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.


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消