17

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;
Community
  • 1
  • 1
Farid-ur-Rahman
  • 1,809
  • 9
  • 31
  • 47

1 Answers1

36

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.

Yoh Deadfall
  • 2,711
  • 7
  • 28
  • 32
Marcel Roma
  • 526
  • 3
  • 3