Kashish Arora
Kashish Arora

Reputation: 908

How to know which command button is clicked in vb.net?

This looks simple to solve, but still not getting to the root of the problem! I inserted 14-15 buttons in a form in vb.net. I combined the Click event of all of them and named the said Event as 'Digits'. I want to know which button is pressed out of those 15 buttons. This is how it looks:

Private Sub Digits(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Subtract.Click, Multiply.Click, Equal.Click, Divide.Click, Clear.Click, Button12.Click, Backspace.Click, B9.Click, B8.Click, B7.Click, B6.Click, B5.Click,
   B4.Click, B3.Click, B2.Click, B1.Click, B0.Click, Addition.Click    

End Sub  

This looks just like an event within another! Is this anyhow possible to know which key is pressed?

Upvotes: 1

Views: 7307

Answers (2)

user4816550
user4816550

Reputation: 21

If you would like to do certain functions based on which button clicked is clicked, you can write an if statement for each handle that you wish to use.

Private Sub Digits(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Subtract.Click, Multiply.Click, Equal.Click, Divide.Click, Clear.Click, Button12.Click, Backspace.Click, B9.Click, B8.Click, B7.Click, B6.Click, B5.Click, B4.Click, B3.Click, B2.Click, B1.Click, B0.Click, Addition.Click
    If sender.name.tostring.contains("ButtonName")
             'do something
    else if sender.........
    ....
    End if 

End Sub

By using the contains option, you do not need to type the entire handle name. This could also allow you to choose the same action for similar buttons such as

if sender.name.tostring.contains("mult") then 
   'multiply
if sender.name.tostring.contains("B") then
  'all buttons that B1-B9

Upvotes: 2

Mark Hall
Mark Hall

Reputation: 54562

Your sender object is the button that generated the Click Event, just cast it to a button and use it accordingly.

Private Sub Digits(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Subtract.Click, Multiply.Click, Equal.Click, Divide.Click, Clear.Click, Button12.Click, Backspace.Click, B9.Click, B8.Click, B7.Click, B6.Click, B5.Click, B4.Click, B3.Click, B2.Click, B1.Click, B0.Click, Addition.Click
    Dim b As Button = DirectCast(sender, Button)
    'b will be the button that generated the click event

End Sub

Upvotes: 3

Related Questions