locked
Cannot access a disposed object? RRS feed

  • Question

  • Hi, all

      In my program, there are 2 forms -- Form1 and Form2

     On Form1, there is a button "Start", when I click on it, Form2 will appear and start plotting, and the text on the button will be changed to "Stop"...

     When I click on "Stop", Form2 will stop plotting, and the text on button will be "Start" again.

     However, when I close "Form2" and click on "Start" again, the following error will be shown:

       Cannot access a disposed object(object name: "Form2")

    So I can not open a form again if I closed it...

    Is there any way to solve this? I hope I can start "Form2" again by clicking "Start"...

    Now, I just know to disable the "ControlBOx" property and add "Maximize"/"Minimize" function by myself to avoid user closing "Form2"...

    I am searching for better methods!

    Thanks in advance!

    Tuesday, September 19, 2006 9:18 AM

Answers

  • You can create a new instance of Form2 and show that instead. Or if you have to reuse the same instance, you can prevent the form from being closed and just hide it instead.

     

    Tuesday, September 19, 2006 9:27 AM
  • Hi, try this:

    private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)

    {

        e.Cancel = true;

        this.Hide();

    }

     

    HTH

    cheers, farshad

    Tuesday, September 19, 2006 9:58 AM

All replies

  • You can create a new instance of Form2 and show that instead. Or if you have to reuse the same instance, you can prevent the form from being closed and just hide it instead.

     

    Tuesday, September 19, 2006 9:27 AM
  • Thanks Mattias,

     well, how to hide the form when user click  "Close"?

    I'll try!

    Tuesday, September 19, 2006 9:34 AM
  • on the button click event show the form as

    Form2 frm2 = new Form2();

    and use the code  as you have written

     

    Tuesday, September 19, 2006 9:35 AM
  • Thanks for you help, Prasant

    I think to hide the form is better for my application..Since I need to retrive the "Form2"

    I did not know how to hide "Form2" when I click "Close" on the ControlBOx of "Form2"...

     

    Tuesday, September 19, 2006 9:47 AM
  • Hi, try this:

    private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)

    {

        e.Cancel = true;

        this.Hide();

    }

     

    HTH

    cheers, farshad

    Tuesday, September 19, 2006 9:58 AM
  • set the visible property to false. call the Hide()
    Tuesday, September 19, 2006 10:00 AM
  • Thanks farshad!

    I just found the Event of Form_Closing(...)

    You information is what I want!!

    Tuesday, September 19, 2006 10:09 AM