I realize you have an answer but thought it prudent to indicate there is a cleaner way. If interested the following creates buttons and by using the same logic can create any type of control like a ComboBox, TextBox etc.
Full source
https://github.com/karenpayneoregon/forum-questions/tree/master/CreateDynamicControls
Class
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace CreateDynamicControls.Classes
{
public class Operations
{
public static List<Button> ButtonsList { get; set; }
public static int Base { get; set; }
public static int Left { get; set; }
public static int BaseWidth { get; set; }
public static int BaseHeightPadding { get; set; }
public static string BaseName { get; set; } = "Button";
public static EventHandler EventHandler { get; set; }
public static Control ParentControl { get; set; }
public static int Index = 1;
/// <summary>
/// Initialize global properties
/// </summary>
/// <param name="pControl">Control to place button</param>
/// <param name="pBase"></param>
/// <param name="pBaseHeightPadding"></param>
/// <param name="pLeft"></param>
/// <param name="pWidth"></param>
/// <param name="pButtonClick">Click event for button</param>
public static void Internalize(Control pControl, int pBase, int pBaseHeightPadding, int pLeft, int pWidth, EventHandler pButtonClick)
{
ParentControl = pControl;
Base = pBase;
BaseHeightPadding = pBaseHeightPadding;
Left = pLeft;
BaseWidth = pWidth;
EventHandler = pButtonClick;
ButtonsList = new List<Button>();
}
public static void CreateButton(string text = "")
{
var button = new Button()
{
Name = $"{BaseName}{Index}",
Text = text,
Width = BaseWidth,
Location = new Point(Left, Base),
Parent = ParentControl,
Visible = true
};
button.Click += new System.EventHandler(EventHandler);
ButtonsList.Add(button);
ParentControl.Controls.Add(button);
Base += BaseHeightPadding;
Index += 1;
}
}
}
using System;
using System.Linq;
using System.Windows.Forms;
using CreateDynamicControls.Classes;
namespace CreateDynamicControls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Operations.Internalize(this,10,30, 100,100, GenericButtonClick);
}
private void CreateButton_Click(object sender, EventArgs e)
{
Operations.CreateButton(string.IsNullOrWhiteSpace(ButtonTextButton.Text) ? "(empty)" : ButtonTextButton.Text);
}
private void GenericButtonClick(object sender, EventArgs e)
{
var button = (Button) sender;
MessageBox.Show(button.Name);
}
private void ButtonListButton_Click(object sender, EventArgs e)
{
ButtonsListBox.DataSource = Operations.ButtonsList.Select(button => button.Name).ToList();
}
}
}