Just to round out Reed's answer, you can either get the Button
objects from the Form
or other container and add the handler, or you could create the Button
objects programmatically.
If you get the Button
objects from the Form
or other container, then you can iterate over the Controls
collection of the Form
or other container control, such as Panel
or FlowLayoutPanel
and so on. You can then just add the click handler with
AddHandler ctrl.Click, AddressOf Me.Button_Click
(variables as in the code below),
but I prefer to check the type of the Control
and cast to a Button
so as I'm not adding click handlers for any other controls in the container (such as Labels). Remember that you can add handlers for any event of the Button
at this point using AddHandler
.
Alternatively, you can create the Button
objects programmatically, as in the second block of code below.
Then, of course, you have to write the handler method, as in the third code block below.
Here is an example using Form
as the container, but you're probably better off using a Panel
or some other container control.
Dim btn as Button = Nothing
For Each ctrl As Control in myForm.Controls
If TypeOf ctrl Is Button Then
btn = DirectCast(ctrl, Button)
AddHandler btn.Click, AddressOf Me.Button_Click ' From answer by Reed.
End If
Next
Alternatively creating the Button
s programmatically, this time adding to a Panel
container.
Dim Panel1 As new Panel()
For i As Integer = 1 to 100
btn = New Button()
' Set Button properties or call a method to do so.
Panel1.Controls.Add(btn) ' Add Button to the container.
AddHandler btn.Click, AddressOf Me.Button_Click ' Again from the answer by Reed.
Next
Then your handler will look something like this
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
' Handle your Button clicks here
End Sub