Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the ID/Name of a button in a click event. VB.NET

Tags:

vb.net

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

like image 773
16 revs, 12 users 31% Avatar asked Jan 28 '13 16:01

16 revs, 12 users 31%


2 Answers

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.

like image 97
U1199880 Avatar answered Oct 25 '22 01:10

U1199880


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
like image 30
Mark Hall Avatar answered Oct 25 '22 03:10

Mark Hall