Cloning a user control

I am creating a user control for an item that I need to be able to duplicate. I need to be able to create a copy/clone of the object when someone selects it. I have been searching, but I have not found a good way of doing this yet. Any help is appreciated.
Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
It needs to be your own "clone" method...something like:
public class MyControl
    public MyControl MyClone()
        MyControl mc = new MyControl();
        // manually copy the pertinent details:
        mc.XXX = this.XXX;
        mc.YYY = this.YYY;
        mc.ZZZ = this.ZZZ;
        return mc;

Open in new window

slightwv (䄆 Netminder) Commented:
Can you provide a little more detail?

Once the object is available you should just need to instantiate another 'copy' of it.
aceswildab1Author Commented:
I have an object in a viewer. Once a user clicks on that object, I want to take a copy of that object and recreate the object in another portion of the program. My user control does not have a copy method. If I say newControl = oldControl, it just creates a reference in memory. I need it to be a deep copy/clone so that from one control, I'm creating two.
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Mike TomlinsonMiddle School Assistant TeacherCommented:
You'd need to manually code your own Clone() method that returns a new instance of your UserControl with all the pertinent properties and data copied over.
Exactly as Idle Mind said: you make your own Clone() method which first creates a new instance of the object and then copies over each of the attributes which makes it unique.

I dont believe there is a standard "copy" or "clone" function available - as each object has their own properties.
aceswildab1Author Commented:
Thank you for the help. I added a Clone() method to my user control. When I did this and ran it, I got an error that my class was not Serializable, so I added that attribute. When I ran after that, I got the following error:

Type 'System.Windows.Forms.UserControl' in Assembly 'System.Windows.Forms, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable

Do I need to do something else in order to get it to work or are user controls themselves just not able to be cloned?
aceswildab1Author Commented:
That makes sense. Thank you very much for your help. Just ran a couple tests, and they all appear to be working fine.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.