tags:

views:

75

answers:

4

i dispose a object in my code. and i wanna now create it again. how?

Answer is :

private void showToolStripMenuItem_Click(object sender, EventArgs e)
    {
        xpPanelGroup1.CreateControl();
        xpPanelGroup1.Visible = true;
         ...


    }
    private void noShowToolStripMenuItem_Click(object sender, EventArgs e)
            {
                xpPanelGroup1.Visible = false;
                  ...
                xpPanelGroup1.Dispose();
            }
A: 

You should have a look in your design code (the ".designer.cs" file automatically generated by at design time), and try to call it. This is the code run when the widget is instantiated.

lmsasu
But the code generated by the WinForms designer is only designed to be run *once* per instance. Running it multiple times for a single instance will leak lots of USER handles. Run out of those (the limit per process is just 10k) and your process will be killed outright, like a soap bubble bursting. No Dr Watson, no logging, nothing - just *gone*. Not good.
Bevan
+2  A: 

You need to create a new object after you have called Dispose().

But if you want to reuse the object later you should not dispose it, you may try to use Hide or .Visible = false or similar if you temporarily want to hide a control.

Edit: In your code you create a new xpPanelGroup1:

UIComponents.XPPanelGroup xpPanelGroup1 = new UIComponents.XPPanelGroup() ;

but that is only local to the showToolStripMenuItem_Click method. If you just type

xpPanelGroup1 = new UIComponents.XPPanelGroup() ;

you are using the class member, that is the same variable you dispose in the noShow method.
But I still recommend just hiding instead of disposing.

Albin Sunnanbo
+1 on using Hide() or Visible = false or similar. Why? Before calling Dispose() on any WinForms control, you need to make sure you properly remove it from the form - take it out of the relevant Controls list, unhook any events, etc. It can be done - but it's pretty complex to get right, and very easy to end up with a nasty memory leak, or worse.
Bevan
please say another way...i dispose it :|
Dr.jacky
I edited my answer with an error in your code.
Albin Sunnanbo
Just don't dispose it. It gets automatically disposed when the form closes.
Hans Passant
A: 

Perhaps you could just set the object to null instead of disposing it and reassign it to another value when you want to use it again.

Mamta Dalal
Problem is that WinForms controls tend to grab references to each other, often behind the scenes.
Bevan
A: 

Use WeakReference Class of .net

saurabh