Question

I have a C# Form that has a Groupbox. The user must input any desired number (integer) and when the user clicks "ADD", the group box must be duplicated and pasted on the same form based on the number the user inputted. How do I create an exact copy of the GroupBox and paste it in the same form? Please see the attached screenshot.

enter image description here

Any help would be much appreciated. Thanks

I used Sriram's code but the form only adds 2 groupBox:

    private void button1_Click(object sender, EventArgs e)
    {

        int containers = 0;
        int.TryParse(textBox1.Text, out containers);

        for (int i = 0; i < containers; i++)
        {
            flowLayoutPanel1.Controls.Add(groupBox1);
        }
    }
Was it helpful?

Solution

I'll suggest you to create a user control which has the groupbox you shown with the child controls.

Let's call it as MyUserControl so when you create instance of MyUserControl you get all controls with the groupbox.

To show the controls without overlapping each other you can use FlowLayoutPanel which arranges the controls automatically. Then in button click code you'd just write

void addButton_Click(object sender, EventArgs e)
{
    int contaniners = 0;
    int.TryParse(txtContainers.Text, out contaniners);

    for (int i = 0; i < contaniners; i++)
    {
        flowLayoutPanel.Controls.Add(new MyUserControl());
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top