Sachin Gaur
Sachin Gaur

Reputation: 13099

Cannot access disposed object .NET

I have a windows form in .NET that will serve as a wizard to achieve something. This contains 3 steps: Step1, Step2, Step3.

Each step is again actually a user control. Main form contains a panel that display the current Step. When I change among steps then:

1) Dispose the current user control by calling its Dispose() method.
2) Clears the main form panel
3) Initialize the user control of next step and add it into the main panel

Now, the issue is, User control of step one contains one more user control. When I change to another step and come back to step 1, I get following error:

"Cannot access disposed object."

Because I have to first dispose the user control before actually displaying the another step. And when I come back to step 1 and tries to open the user control on step 1, it gives the aforementioned error.

Upvotes: 1

Views: 2728

Answers (2)

Jesse Weigert
Jesse Weigert

Reputation: 4854

Why do you need to dispose the user control? Typically, when the form closes, it will dispose of all of it's child controls for you.

When you call dispose on an object, you are essentially telling it to go away.. you don't want it anymore. You can't change your mind -- once it's disposed, it's gone. Don't try to use it anymore.

Typically, you don't call dispose on an object directly; you should use the "using" pattern to avoid disposing of an object before you need it again, and to ensure the object is disposed once you are done with it.

Upvotes: 1

Jesse Smith
Jesse Smith

Reputation: 380

Everything in the Controls collection of a Control is disposed when the control is disposed. So if you need to reuse those user controls, you'll need to remove them from the parent user control before disposing it.

You don't actually have to dispose the user control before displaying the next one. You can just remove it from the main form and put the new one on the main form when the step changes. Keep your user controls in a list or a dictionary and dispose them all when the main form is closing.

Upvotes: 1

Related Questions