Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone Controls - C# (Winform) [duplicate]

Tags:

c#

winforms

Possible Duplicate:
It is possible to copy all the properties of a certain control? (C# window forms)

I have to create some controls similar to a control created as design time. The created control should have same properties as a predefined control, or in other words I want to copy a control. Is there any single line of code for that purpose? or I have to set each property by a line of code? I am doing right now is:

        ListContainer_Category3 = new FlowLayoutPanel();
        ListContainer_Category3.Location = ListContainer_Category1.Location;
        ListContainer_Category3.BackColor = ListContainer_Category1.BackColor;
        ListContainer_Category3.Size = ListContainer_Category1.Size;
        ListContainer_Category3.AutoScroll = ListContainer_Category1.AutoScroll;
like image 294
Farid-ur-Rahman Avatar asked Apr 22 '12 08:04

Farid-ur-Rahman


1 Answers

Generally speaking you can use reflection to copy the public properties of an object to a new instance.

When dealing with Controls however, you need to be cautious. Some properties, like WindowTarget are meant to be used only by the framework infrastructure; so you need to filter them out.

After filtering work is done, you can write the desired one-liner:

Button button2 = button1.Clone();

Here's a little code to get you started:

public static class ControlExtensions
{
    public static T Clone<T>(this T controlToClone) 
        where T : Control
    {
        PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        T instance = Activator.CreateInstance<T>();

        foreach (PropertyInfo propInfo in controlProperties)
        {
            if (propInfo.CanWrite)
            {
                if(propInfo.Name != "WindowTarget")
                    propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
            }
        }

        return instance;
    }
}

Of course, you still need to adjust naming, location etc. Also maybe handle contained controls.

like image 160
Marcel Roma Avatar answered Sep 29 '22 04:09

Marcel Roma