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

前端 未结 3 1185
忘掉有多难
忘掉有多难 2020-12-31 09:00

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

相关标签:
3条回答
  • 2020-12-31 09:30

    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
    
    0 讨论(0)
  • 2020-12-31 09:32

    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.

    0 讨论(0)
  • 2020-12-31 09:34

    Even simpler:

    If sender is btnAnswer1 then ...

    0 讨论(0)
提交回复
热议问题