14

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

pluke
  • 3,832
  • 5
  • 45
  • 68

3 Answers3

20

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.

U1199880
  • 907
  • 1
  • 10
  • 21
  • 10
    [Better use `DirectCast` instead of `CType`](http://stackoverflow.com/a/103285/1968), it makes the intent clearer: we want to *downcast* a dynamic type, not *convert* a static type. – Konrad Rudolph Jan 28 '13 at 16:46
3

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
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
  • 4
    [Better use `DirectCast` instead of `CType`](http://stackoverflow.com/a/103285/1968), it makes the intent clearer: we want to *downcast* a dynamic type, not *convert* a static type. – Konrad Rudolph Jan 28 '13 at 16:46
-3

Even simpler:

If sender is btnAnswer1 then ...