Question

I'm getting ObjectDisposedException was unhandled with message Cannot access a disposed object.

This happens when initialize this child form at the beginning of my class by MyForm myForm = new MyForm(); and then adding some text to my text box of that form by myForm.txtBox.AppendText("Text"); and then opening my new form my form by using some button with code myForm.Show();. Now when my job is done I can close the form. Now, when I want to display the data again I'm getting that exception.

I want to keep the content of text box in my new form, but it seems like there is a problem that I haven't disposed everything in it.

How to avoid this so I can view the new forms content any time I press button?

Was it helpful?

Solution

From the MSDN documentation on Form.Close:

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.

You could capture the Form.Closing event on the form, cancel the event, and hide the form instead of Closeing it.

OTHER TIPS

The problem appears to be that you're creating an instance of MyForm at the start of the class and re-using it every time the button is pressed. That won't work unfortunately. Once the form is closed it will be disposed and hence no longer valid. It will throw the next time you try and show it.

The easiest way to work around this is to create and display the form entirely within the button click event. Don't reuse it's instance between clicks.

void OnButtonClick(object sender, EventArgs e) {
  using (MyForm myForm = new MyForm()) {
    myForm.txtBox.AppendText("Test");
    myForm.ShowDialog(this);
  }
}

If there is some state you need to keep between clicks, such as the text, then store that but not the Form instance.

You should capture the FormClosing event as M.Babcock said but I'd also recommend you to check the close reason, if te user requested it, you can cancel and do whatever you want:private

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;

        // Make your form dissappear of whatever you want
    }
}

Otherwise you won't be able to close it in case you want to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top