Dynamic Buttons Controls Event Handling WinForms Windows Forms

Dynamic Buttons Controls Event Handling In Windows Forms Or Winforms Applications In .Net 2.0,3,5. C# And VB.NET.

Dynamic Buttons in winforms
many times we need to create controls at runtime or through code behind depending on the real time scenario.

In this post i am going to explain how to add dynamic buttons at runtime and handle the Button Click event in winforms or windows forms applications.

I am creating 3 buttons on Form_Load event and placing them on the form.



Write this code in Load event of windows form.


C# Code

private void Form1_Load(object sender, EventArgs e)
        {
            int x = 50, y = 50;
            for (int i = 1; i <= 3; i++)
            {
                Button btnDynamic = new Button();
                btnDynamic.Location = new System.Drawing.Point(x, y);
                btnDynamic.Name = " Dynamic Button " + i;
                btnDynamic.Size = new System.Drawing.Size(100, 50);
                btnDynamic.Text = btnDynamic.Name;
                Controls.Add(btnDynamic);
                x += 100;
                btnDynamic.Click += new EventHandler(this.DynamicButtonClick);
            }
            
        }

Here x and y are horizontal and vertical cordinates where dynamically created buttons will be placed.

x is incremented by 100 each time so that buttons don't get placed overlapped.

when button is created, eventhandler for Click Event of button is associated with it in last line of above mentioned method.

Now write below mentioned method signature in the code behind

private void DynamicButtonClick(object sender, EventArgs e)
   {

   }

Method name must be exactly the same u mentioned in eventhandling code, as It's case sensitive. Write this code inside this method

private void DynamicButtonClick(object sender, EventArgs e)
        {
            Button btnDynamic = (Button)sender;
            btnDynamic.Text = "You Clicked" + btnDynamic.Name;
                      
        }

VB.NET Code

Private Sub Form1_Load(sender As Object, e As EventArgs)
 Dim x As Integer = 50, y As Integer = 50
 For i As Integer = 1 To 3
  Dim btnDynamic As New Button()
  btnDynamic.Location = New System.Drawing.Point(x, y)
  btnDynamic.Name = " Dynamic Button " & i
  btnDynamic.Size = New System.Drawing.Size(100, 50)
  btnDynamic.Text = btnDynamic.Name
  Controls.Add(btnDynamic)
  x += 100
  btnDynamic.Click += New EventHandler(AddressOf Me.DynamicButtonClick)
 Next

End Sub

Private Sub DynamicButtonClick(sender As Object, e As EventArgs)
 Dim btnDynamic As Button = DirectCast(sender, Button)
 btnDynamic.Text = "You Clicked" + btnDynamic.Name

End Sub


Build the application and run.

If you like this post than join us or share

Find More Articles