In this short code snippet article I will explain how to create Dynamic Button controls at runtime and also attach Click event handler to the dynamically created buttons
C#
//Counter for Dynamic Buttons.
int DynamicButtonCount = 1;
//This event generates Dynamic Buttons.
private void btnGenerate_Click(object sender, EventArgs e)
{
string name = "Dynamic Button_" + DynamicButtonCount;
Button btnDynamicButton = new Button();
btnDynamicButton.Name = name;
btnDynamicButton.Text = name;
btnDynamicButton.Size = new System.Drawing.Size(200, 30);
btnDynamicButton.Location = new System.Drawing.Point(40, DynamicButtonCount * 40);
btnDynamicButton.Click += new EventHandler(this.btnDynamicButton_Click);
Controls.Add(btnDynamicButton);
DynamicButtonCount++;
}
//This event is triggered when a Dynamic Button is clicked.
protected void btnDynamicButton_Click(object sender, EventArgs e)
{
Button dynamicButton = (sender as Button);
MessageBox.Show("You clicked. " + dynamicButton.Name);
}
VB.Net
'Counter for Dynamic Buttons.
Dim DynamicButtonCount As Integer = 1
'This event generates Dynamic Buttons.
Private Sub btnGenerate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGenerate.Click
Dim name As String = ("Dynamic Button_" & DynamicButtonCount)
Dim btnDynamicButton As Button = New Button
btnDynamicButton.Name = name
btnDynamicButton.Text = name
btnDynamicButton.Size = New System.Drawing.Size(200, 30)
btnDynamicButton.Location = New System.Drawing.Point(40, (DynamicButtonCount * 40))
AddHandler btnDynamicButton.Click, AddressOf Me.btnDynamicButton_Click
Controls.Add(btnDynamicButton)
DynamicButtonCount = (DynamicButtonCount + 1)
End Sub
'This event is triggered when a Dynamic Button is clicked.
Protected Sub btnDynamicButton_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim dynamicButton As Button = CType(sender, Button)
MessageBox.Show(("You clicked. " + dynamicButton.Name))
End Sub
Demo
Downloads