1

我正在做一个简单的计算器。我厌倦了在每个按钮中分配事件处理程序,它效率低下。

我只希望一个事件处理程序在按下时获取按钮内的文本。

怎么做?

  Private Sub num1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles co.Click
    numPressed = num1.Text
End Sub
4

3 回答 3

5

在您的点击事件中:

Dim button as Button = sender
Dim theTextYouWant as String = button.Text
于 2013-03-11T10:40:09.250 回答
2

您可以button's click event像这样在运行时有效地添加句柄,

我假设您的buttons内部是panel被调用的PnlBtns

'Traversing through panel and adding a common handler for buttons
For each ctrl in PnlBtns.controls
 If TypeOf ctrl is button then
   AddHandler ctrl.Click, AddressOf CommonClickHandler
 end if
Next

'Common Handler for all of your buttons.
Private Sub CommonClickHandler(ByVal sender As System.Object, ByVal e As System.EventArgs)
  MsgBox(ctype(sender,button).text)
End Sub
于 2013-03-11T11:23:16.907 回答
2

只需添加您要使用函数处理的所有事件,并检测在其中按下了哪个按钮:

Private Sub num1_Click(sender As Object, ByVal e As EventArgs) _
Handles co.Click, co2.Click, co3.Click 'etc
    Dim btn As Button = CType(sender, Button)
    numPressed = btn.Text
End Sub
于 2013-03-11T10:49:39.890 回答