Windows Forms: Dynamically add button click event in C#

This post shows you how to dynamically add button and click event in C# Windows Forms Application.

Dragging a Button control from the Visual Studio toolbox into your form designer, then add a click event handler to the button control.

C# Dynamically add button click event

c# dynamically add button click event

Each time you click the add button, a button is dynamically created and added to the form with the click event.

C# Dynamically add button to form

int index = 1;
//c# dynamic add button
private void btnAddButton_Click(object sender, EventArgs e)
{
    string name = $"Button_{index++}";
    Button btn = new Button() { Name = name, Text = name };
    btn.Size = new System.Drawing.Size(100, 25);
    btn.Location = new System.Drawing.Point(190, index * 35);
    btn.Click += Btn_Click;
    this.Controls.Add(btn);
}

and don't forget to implement Btn_Click event handler.

private void Btn_Click(object sender, EventArgs e)
{
    Button button = (sender as Button);
    MessageBox.Show($"{button.Name} clicked.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Through this example, you have learned how to dynamically create a button as well as dynamically add events to the button