Zdravko Crncevic
Zdravko Crncevic

Reputation: 21

Get the name of the button that triggered the event

I have an event handler that handles the click event of multiple buttons:

Private Sub primeHandler(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _2s.Click, _3s.Click, _4s.Click, _5s.Click, _6s.Click

End Sub

_2s, _3s, etc are all buttons. Now I need a way to determine which button triggered the event and also get the button's name as string. Any way to do that? Thanks

Upvotes: 2

Views: 6900

Answers (2)

Blackwood
Blackwood

Reputation: 4534

You can cast sender to type Button and access the Name property.

Private Sub primeHandler(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _2s.Click, _3s.Click, _4s.Click, _5s.Click, _6s.Click
    Dim myButton As Button = CType(sender, Button)
    Dim myName As String = myButton.Name
End Sub

Upvotes: 5

Ken White
Ken White

Reputation: 125748

Use sender - it's what it's designed to do.

MessageBox.Show((sender as Button).Name);

If you're going to use it more than once, assign it to a variable to make it easier.

var button = (sender as Button);
MessageBox.Show(button.Name);

Upvotes: 2

Related Questions