我正在尝试将自己的参数( 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
由于
答案 0 :(得分:0)
你不能改变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
如果需要,您可以从名称派生实际索引。
Dim Index as Integer = CInt(ButtonName.Substring(7))
答案 1 :(得分:0)
除了其他答案外,您的按钮还有一个名为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