tags:

views:

393

answers:

2

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.

+1  A: 

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.

Jesse Smith
When I tried the approach of not disposing the control, then I am facing a new issue. The Event, where I am calling the user control placed on Step1 to display, is called two times. Can you please tell me the reason for it?
Sachin Gaur
I just realised that not exactly two times.. It is getting called as many times I swtich to another step and come back to step 1.
Sachin Gaur
+1  A: 

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.

Jesse Weigert