SYSK 122: Clone a WinForms Control with all its Properties

As you know, WinForms controls (e.g. TextBox, ComboBox, etc.) are not serializable.  So, how do you create a copy of a control?  The other day I needed to do just that, and here is the code I ended up with (note: it has not yet been thoroughly tested, so use at your own risk):

 

public Control CloneControl(Control sourceControl)

{

    Control result = null;

    try

    {

        Type t = sourceControl.GetType();

        result = (Control) Activator.CreateInstance(t);

        PropertyDescriptorCollection sourceProps = TypeDescriptor.GetProperties(sourceControl);

        PropertyDescriptorCollection destProps = TypeDescriptor.GetProperties(result);

        for(int i=0; i< sourceProps.Count; i++)

        {

            if (sourceProps[i].Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))

            {

                object sourceValues = sourceProps[i].GetValue(sourceControl);

                if ((sourceValues is IList) == true)

                {

                    foreach (object child in (sourceValues as IList))

                    {

                        Control childCtrl = CloneControl (child as Control);

                        IList destValues = destProps[i].GetValue(result) as IList;

                        System.Diagnostics.Debug.Assert(destValues != null);

                        if (destValues != null)

           destValues.Add(childCtrl);

                    }

                }

            }

            else

            {

                destProps[sourceProps[i].Name].SetValue(result, sourceProps[i].GetValue(sourceControl));

            }

        }

   return result;

    }

    catch(Exception ex)

    {

         // Your exception handling here…

    }

}