【问题标题】:Get text inside buttons when pressed using only one event handler [closed]仅使用一个事件处理程序按下时在按钮内获取文本[关闭]
【发布时间】:2013-03-11 10:33:19
【问题描述】:

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

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

怎么做?

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

【问题讨论】:

  • 你能分享你的代码吗?
  • 您确定要这样做吗?如果您尝试过,我认为您无法再将您的演示文稿与您的实现结合起来。

标签: vb.net button


【解决方案1】:

在您的点击事件中:

Dim button as Button = sender
Dim theTextYouWant as String = button.Text

【讨论】:

    【解决方案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
    

    【讨论】:

      【解决方案3】:

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

      我假设您将 buttons 放在名为 PnlBtnspanel 中。

      '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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 2016-03-30
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 2013-07-03
        相关资源
        最近更新 更多