How to duplicate a panel of control dynamically?

108 Views Asked by At

I want to duplicating panel with same style of other panel depend on integer.

For example

Integer = 3

so I have the original panel and copy it three time with the same style using C#

1

There are 1 best solutions below

3
Jonathan Applebaum On

You can clone control in WinForms using PropertyInfo[].
Here is a method to duplicate panel control:

private Panel GetClonedPanel(Panel panel)
{
    PropertyInfo[] controlProperties = typeof(Panel).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    Panel cloned = Activator.CreateInstance<Panel>();

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

    return cloned;
}

Implementation:

private void button1_Click(object sender, EventArgs e)
{
    int inTeger = 3;
    int x = panel1.Location.X;
    for (int i = 0; i <= inTeger; i++)
    {
        // Clone the control
        Panel cloned = GetClonedPanel(panel1);
        x = x + cloned.Width + 2;
        // Add it to the form
        cloned.Location = new Point(x, panel1.Location.Y);
        this.Controls.Add(cloned);
    }
}

Output:

enter image description here