I'm adding buttons to form at runtime using the following code :
Private Sub AddNewButton(ByVal btnName As String, ByVal btnText As String)
Dim myButtons As New VIBlend.WinForms.Controls.vButton
With myButtons
.Size = New Size(200, 60)
.Visible = True
.Location = New Point(55, 33)
.Text = btnText
.Name = btnName
.Font = New Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point)
End With
AddHandler myButtons.Click, AddressOf btnName & "_Click"
btnsPanel.Controls.Add(myButtons)
End Sub
Code works fine but Vb.net doesn't allow me to assign AddressOf a sub procedure using variable AddressOf btnName & "_Click"
says AddressOf operand must be the name of method
, the problem is I don't know which button is going to be created and which procedure is it going to call, I want to assign AddressOf procedure using variable
Is it possible or do I have any other choice ?
You can (and should) use the same event handler for all of the buttons.
AddHandler myButtons.Click, AddressOf btn_Click
You can get the name in the handler in this way:
Private Sub btn_Click(sender As Object, e As EventArgs)
Dim button = DirectCast(sender, Button)
Dim name As String = button.Name ' you can also use the Tag property
End Sub