1
votes

I am creating many usercontrols in an windows application in C# 3.5. I want to copy any usercontrol and paste it on another location of the MDIForm. Similarly in case of Cut option. I am using these three options in a contextmenustrip. And theses options are visible when I right click on the usercontrol. Can anyone tell me how It will be done at run time?

2

2 Answers

1
votes

That requires giving the controls a new Parent. Explicitly supported by Winforms, they can even have no parent, quite a trick. You can do it directly by assigning the Parent property. Or by adding the control to another Controls collection, it will be automatically removed from the one it was in before.

Be careful, this flexibility comes with a price. It is also a source of a nasty leak that can crash your program after a while. That's caused by the no-parent trick, otherwise triggered by a Cut without a subsequent Paste. If you use Controls.Remove() or Controls.Clear() then the control is moved to the 'parking window', an invisible window created by the Winforms plumbing that acts as a temporary host. If you then don't either move the control to another parent or forget to call its Dispose() method then the control will live forever. Until your program runs out of resources or the user terminates the program.

The out of resources bomb ("cannot create window") typically happens after a few hours so is easily missed when debugging. You can see it in TaskMgr.exe, Processes tab. View + Select Columns and tick USER objects. Also tick GDI Objects and Handles to feel good about your program not leaking.

If you put the controls on a Panel then you can move them all together with just a single line of code by moving the panel.

0
votes

You could remove the control from the ControlCollection in case of cut and cache it to add that control to some other form when pasted like you could do

 panel1.Controls.Add(newPanelButton);// To add, you might have to change the control `Location` as per your need

 panel1.Controls.Remove(newPanelButton);//To remove

In case of having cut/copy effect on the same form you could just change the Location of the control to the new location where you want to paste that control.