Destroying a control fails.-Collection of common programming errors


  • msdn

    I’m having difficulties while destroying a usercontrol. I created my own control, and am using it in an application. The variable is always the same. I create and destroy the object multiple times, but the control fails to disappear, and instead reemerges at it’s original coordinates the first time it was created. It’s resizable and movable at runtime. When I click outside of it it’s supposed to be destroyed an nullified. It does disappear but reemerges as I said at it’s original coordinates. I’m using usercontrol.Destroy() for that, but first I set the usercontrol.visible to false. Am I missing something? Shouldn’t an object just disapper when it’s destroyed, in this case a control, or is this more complicated than I thought?


  • msdn1 Hi,

    Do you remove the control reference from the parent Controls collection?


  • msdn2 Your question is very unclear.  UserControl doesn’t have a Destroy() method.   To remove a control from its container you have to Remove() it from its container’s Controls collection, then Dispose() it so the window handle is destroyed.  For example:   this.Controls.Remove(userControl1);   userControl1.Dispose();

  • msdn3 I think i tried that like this:

    panel1.Controls.Remove(cropTracker);

    and this is how I initialized it, by giving it two parameters. It’s like a CRectTracker in MFC. There are two parameters: the control it’s supposed to resize and the reference to the form which i need to access objects on the main form from the tracker.

    RectTracker cropTracker =

    panel1.Controls.Add(cropTracker);

    new RectTracker(cropTracker, this);


  • msdn4 Your question is very unclear.  UserControl doesn’t have a Destroy() method.   To remove a control from its container you have to Remove() it from its container’s Controls collection, then Dispose() it so the window handle is destroyed.  For example:   this.Controls.Remove(userControl1);   userControl1.Dispose();

  • msdn5

    It works now but I’m having some other problems which are too complex to describe. I’ll try to fix that. Sorry for desturbing you with such trivial questions. Thanks everyone.


  • msdn6

    Thank you Hans. I wanted to write Dispose but somehow I wrote Destroy.