I have an event in VB.NET to handle several button clicks at once. I need to know which button from the selection kicked off the event. Any ideas how to do this? My code is below:
Private Sub Answer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnswer1.Click, btnAnswer2.Click, btnAnswer3.Click, btnAnswer4.Click
'output button ID that caused event
End Sub
I've tried sender.Id, e.Id, sender.name, e.name. None of them work
You have to cast the sender to the object type expected.
Dim btn As Button = CType(sender, Button)
Then you can access what you need.
Try CType(Sender, Button).Name
. Sender is an Object you need to cast to the calling Type in this case Button. If you need more properties from the Sender then use U1199880 's answer. But usually when I am trying to handle multiple clicks I will use the Tag property, assign an index to it. Something like this.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
Dim index As Integer
If Not Integer.TryParse(CType(sender, Button).Tag.ToString, index) Then Exit Sub
Select Case index
Case 0
Case 1
Case 2
....
End Select
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With