Saturday, December 22, 2018

Windows Form Cannot Access a Disposed Object?

閱讀中文版

What does this mean?
System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Form1'.
You are getting this exception probably because you want to Show() a windows form that was closed by user. The user likely closed the form by clicking the close button on the title bar. Close() is called when the form is closing and Dispose() is subsquently called. Now you have a disposed form that really not useful any more.
The fix is quite simple, just new the Form again. If you are not sure if the form has to be created again, check for IsDisposed.
if (form1?.IsDisposed == true)
{
    form1 = new Form1();
}
If you really want to hide the form instead of closing it and hence disposed, This is what you can do on the Closing event of the form.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true; // Cancel the closing sequence
    Hide();          // Hide the form
}

No comments:

Post a Comment