I am making a program where I need to dynamically add buttons to a form. When the form loads anywhere from 0-30 buttons will need to be loaded. When a button is pressed it needs to run a common function, but pass a unique parameter to the function so it knows what button was pressed. I have looked on the internet and I have found ways to add buttons during run time, but they always have to predetermined before the program is complied.

Here is an example of what i want my program to do.

On load

create a button for each id# in an array

when that button is pressed it passes that id# to a function as a parameter.

Thanks in advance

I would use button's Tag property to store information about which button have been clicked. Here's the full code

Public Class Form1

  Private Sub NewButton(ByVal ButtonNumber As Integer)
    ' Create a new button
    Dim oButton As Button

    oButton = New Button
    ' Set properties. Change these as you like and set other props if needed
    oButton.Enabled = True
    oButton.Location = New Point(ButtonNumber * 30, ButtonNumber * 30)
    oButton.Name = "MyButton" & ButtonNumber.ToString
    oButton.Size = New Size(75, 23)
    oButton.Text = "Button" & ButtonNumber.ToString
    oButton.Visible = True
    ' Use Tag property to store "which button" information
    oButton.Tag = ButtonNumber
    ' Add button click handler
    AddHandler oButton.Click, AddressOf onButtonClick
    ' Add to this forms controls collection
    Me.Controls.Add(oButton)

  End Sub

  Private Sub MyFunc(ByVal ButtonNumber As Integer)
    ' Do your stuff here

    MessageBox.Show("You clicked button: " & ButtonNumber.ToString, "Click", MessageBoxButtons.OK, MessageBoxIcon.Information)

  End Sub

  Private Sub onButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    ' Handle button click and check which button is clicked
    Dim ButtonNumber As Integer

    ' Get Tag property. Cast sender to Button first
    If CType(sender, Button).Tag IsNot Nothing Then
      ' Check that button's Tag property contains a valid integer
      If Integer.TryParse(CType(sender, Button).Tag.ToString, ButtonNumber) Then
        ' Now we have a valid button number to be used
        MyFunc(ButtonNumber)
      End If
    End If

  End Sub

  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Create buttons dynamically on form load
    Dim i As Integer

    For i = 0 To 30
      NewButton(i)
    Next i

  End Sub

End Class

I tried to comment the code so you can easily modify it. The key portion of the code is onButtonClick event handler. I used integers as button "id" but you can use some other data type if needed.

HTH

Hi! Nice to hear that you got answer to your problem. Could you please mark the thread as solved. Thank you!

This article has been dead for over six months. Start a new discussion instead.