如何知道在vb.net中点击了哪个命令按钮?

时间:2013-12-08 15:50:54

标签: vb.net winforms visual-studio visual-studio-2008

这看起来很简单,但仍然没有找到问题的根源! 我在vb.net中的表单中插入了14-15个按钮。我结合了所有这些事件的Click事件,并将所述事件命名为“数字”。 我想知道这15个按钮中按哪个按钮。 这是它的外观:

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  

这看起来就像另一个事件!这无论如何都可以知道按下了哪个键?

2 个答案:

答案 0 :(得分:2)

您的发件人对象是生成Click事件的按钮,只需将其转换为按钮并相应地使用它。

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

答案 1 :(得分:1)

如果您希望根据单击的按钮执行某些功能,则可以为要使用的每个句柄编写if语句。

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

通过使用contains选项,您无需键入整个句柄名称。这也可以让您为类似的按钮选择相同的操作,例如

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