Finding out what button was pressed??

AB_Bill

New member
Joined
Sep 13, 2011
Messages
1
Programming Experience
1-3
Hi guys, first time on this forum...
I tried your code and got it to work - put buttons on my form, etc. I included the AddHandler for each btnNew(index):

Public Class ButtonAdd
Private btnNew(9) As System.Windows.Forms.Button

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim intLoop As Integer

For intLoop = 0 To 9
btnNew(intLoop) = New Button
With btnNew(intLoop)
.Text = "ButtonText" & CStr(intLoop)
.Name = "ButtonName" & CStr(intLoop)
.SetBounds(10, 50 * (intLoop + 1), 120, 40)
AddHandler .Click, AddressOf Me.Hello_Click
End With
Next

Me.Controls.AddRange(btnNew)
End Sub

Private Sub Hello_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show("Button: " & sender.GetType.Name.ToString & " was pressed.")
End Sub
End Class

In my Hello_Click sub, how can I find out what button was pressed? I can't use the text field as that will change and that is about the only field I CAN detect (sender.ToString). Sender.GetType.Name gives me "Button" for every button. This is so close to working, any ideas/suggestions???

Thanks!
 
'sender' event parameter identifies which object raised the event, and here is it Button objects. Use DirectCast or CType to cast the sender object to a more specific type such as Button, then you can access properties like the Text property or Name property of that control.
DirectCast Operator (Visual Basic)
CType Function (Visual Basic)
 
Back
Top