Here's a general solution of adding and deleting UserControls based on the current value of a NumericUpDown Control. There are two Buttons, btnAdd, and btnDelete.
You can modify the code in the loops inside the Click EventHandlers for the two Buttons to do what you want to do:
private int nOfUserControls;
private void btnAdd_Click(object sender, EventArgs e)
{
for (int i = 0; i < nOfUserControls; i++)
{
AUserControl newUserControl = new AUserControl();
newUserControl.ucButton.Text = "button " + i.ToString();
newUserControl.Location = new Point(10, ((i + 1) * 40));
pnlUCContainer.Controls.Add(newUserControl);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (nOfUserControls > pnlUCContainer.Controls.Count)
{
nOfUserControls = pnlUCContainer.Controls.Count;
numericUpDown1.Value = nOfUserControls;
}
for (int i = 0; i < nOfUserControls; i++)
{
pnlUCContainer.Controls.RemoveAt(0);
}
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
nOfUserControls = Convert.ToInt32(numericUpDown1.Value);
}
The very simple UserControl used here has only a Button on it:
public partial class AUserControl : UserControl
{
public AUserControl()
{
InitializeComponent();
ucButton = button1;
}
public Button ucButton { get; private set; }
}