【问题标题】:How to send my own parameters to AddHandler如何将我自己的参数发送到 AddHandler
【发布时间】:2014-01-02 15:00:05
【问题描述】:

我正在尝试将我自己的参数(Index As Integer 而不是 sender As Object, e As EventArgs)发送到 AddHandler。这是我的代码:

Dim Button_ as Button
For Index=0 To 9
    Button_ = New Button()
    Button_.Left = 10
    Button_.Top = (Index * 30) + 10
    Button_.Width = 100
    Button_.Height = 20
    AddHandler Button_.Click, AddressOf Button_Click(Index)
    Me.Controls.Add(Button_)
Next

Sub Button_Click(Index As Integer)
    'Do stuff here...
End Sub

谢谢

【问题讨论】:

    标签: .net vb.net events handler


    【解决方案1】:

    您无法更改 Click 事件处理程序的签名,但如果您指定了哪个按钮的名称(我假设它是一个 WinForm 按钮),则可以检测到哪个按钮被单击。

    Dim Button_ as Button
    For Index=0 To 9
        Button_ = New Button()
        Button_.Left = 10
        Button_.Top = (Index * 30) + 10
        Button_.Width = 100
        Button_.Height = 20
    
        Button_.Name = "Button_" & Index.ToString()
    
        AddHandler Button_.Click, AddressOf Button_Click
        Me.Controls.Add(Button_)
    Next
    

    然后您可以像这样使用标准签名:

    Sub Button_Click(sender As Object, e As EventArgs)
         Dim Button_ as Button = CType(sender, Button)
         Dim ButtonName = Button.Name
    End Sub
    

    如果需要,您可以从 Name 导出实际索引。

    Dim Index as Integer = CInt(ButtonName.Substring(7))
    

    【讨论】:

    • 很高兴它有帮助。如果有用,请将解决方案标记为答案
    【解决方案2】:

    除了其他答案,您的按钮还有一个名为Tag 的属性,它被定义为一个对象。当我需要使用带有控件数组的通用事件处理程序时,我通常会使用此属性,您会使用它。

    Dim Button_ as Button
    For Index=0 To 9
        Button_ = New Button()
        Button_.Left = 10
        Button_.Top = (Index * 30) + 10
        Button_.Width = 100
        Button_.Height = 20
        Button_.Tag = Index
        AddHandler Button_.Click, AddressOf Button_Click
        Me.Controls.Add(Button_)
    Next
    
    Private Sub Button_Click(sender As Object, e As EventArgs)
        Dim i As Integer = CInt((CType(sender, Button).Tag))
        ' Use your index accordingly
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多