0

I've a custom control which gets updated continuously with external data. I've two panels, one of them contains the custom control.

I want to move the custom control from one panel to another upon a button click and it looks like the control is getting deleted after call to Controls.Remove

Panel1.Controls.Remove(customControl); // looks like this delete that customControl object
Panel2.Controls.Add(customControl); // Throws an exception "Object reference not set to instance of an object"

So my question is how can I reuse my customControl after call to Remove. Please note that:

1) I can't create two instance of customControl because of some side effects.

2) If I create a new instance of customControl after call to Remove, I'll lose the old data which is not desirable.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Aamir
  • 1,974
  • 1
  • 14
  • 18
  • I think (though I am not 100% sure) that if you just do the add it will automatically remove it from where it was before. – Chris Nov 10 '15 at 12:22
  • To add to that https://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.add%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 says "If the Control is already a child of another control it is removed from that control before it is added to another control." – Chris Nov 10 '15 at 12:24
  • I guess `Panel2` is `null`? This behavior is not related to removing and adding the controls in my opinion. Something else is the problem. – Patrick Hofman Nov 10 '15 at 12:30
  • 1
    That cannot be caused by Remove() itself. My crystal ball says that this "custom control" uses the ParentChanged event incorrectly. There is very little point in forcing us to guess at this when you can trivially show us the exception's stack trace or spend some time minimizing the custom control's code. – Hans Passant Nov 10 '15 at 12:30

0 Answers0