From your comments, I understand that your ideas regarding adding buttons at runtime are not too clear and thus I am including a small code which hopefully will help you on this front. Start a new project and put a Panel (Panel5
) and a Button (AddButtons
) on it, and write this code:
Dim lastButtonIndex, lastLeft, lastTop As Integer
Private Sub Button_Click(sender As System.Object, e As System.EventArgs)
Dim curButton As Button = DirectCast(sender, Button)
If (curButton.Name = "Button1") Then
'do Button1 stuff
End If
'etc.
End Sub
Private Sub addNewButton()
lastButtonIndex = lastButtonIndex + 1
lastLeft = lastLeft + 5
lastTop = lastTop + 5
Dim Button As New Button
With Button
.Name = "Button" + lastButtonIndex.ToString()
.Text = "Button" + lastButtonIndex.ToString()
.Width = 50
.Height = 25
.Left = lastLeft
.Top = lastTop
AddHandler .Click, AddressOf Button_Click
End With
Me.Panel5.Controls.Add(Button)
End Sub
Private Sub ButtonAddButtons_Click(sender As System.Object, e As System.EventArgs) Handles AddButtons.Click
addNewButton()
End Sub
This code will add a new button to the panel every time you click on AddButtons
. All the buttons will have an associated Click Event
(the same one for all of them): Button_Click
. The way to know which button is the current one inside this method is via sender
, as shown in the code (you can put as many conditions as buttons. The names are given sequentially starting from 1; but you can take any other property as reference, curButton
is the given Button Control
).
Bear in mind that one of the problems you have to take care of is the location of the buttons. The code above has a very simplistic X/Y values (Left
/Top
properties) auto-increase which, logically, will not deliver what you want.