When trying to add an event handler to a dynamically created button I get an an error:
Dim Itm As New Button
Itm.Name = "Itm" & i
Itm.Height = 62
Itm.Width = 159
Itm.Text = Temp(i, 0).ToUpper
Itm.Left = (F * 165)
Itm.Visible = True
Itm.BackColor = Colour
Itm.ForeColor = Color.Black
AddHandler Itm.Click, AddressOf Me.Itm_Click
Me.pnlItemButton1.Controls.Add(Itm)
i = i + 1
If i > Temp.Length - 1 Then
GoTo Exit1
End If
I get an error on the AddressOf line:
"Item_Click is not a member of windowsapplication1.main"
I feel this is because I have set the name to be "Itm" & i
but using AddressOf Me.Itm(i)_Click
also presents an error. Any thoughts?
You have to declare the event handler Itm_Click
and it must be accessible.
For example (presuming that your array Temp
exists somewhere):
Public Class Demo
Protected Sub Itm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Public Sub DemoMethod()
For i As Int32 = 1 To Temp.Length - 1
Dim Itm As New System.Windows.Forms.Button()
Itm.Name = "Itm" & i
Itm.Height = 62
Itm.Width = 159
Itm.Text = Temp(i, 0).ToUpper
Itm.Left = (F * 165)
Itm.Visible = True
Itm.BackColor = Colour.White
Itm.ForeColor = Color.Black
AddHandler Itm.Click, AddressOf Me.Itm_Click
Me.pnlItemButton1.Controls.Add(Itm)
Next
End Sub
End Class
You can use this event handler for all dynamically created buttons. You get the button that was clicked from the sender
argument:
Protected Sub Itm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim actualButton = Ctype(sender, System.Windows.Forms.Button)
Dim name = actualButton.Name
End Sub