0

我试图了解为什么我的 AddHandler 不起作用。

如果按钮总是在同一个表单上,但将来可能不会,我找到了一种解决方法。

我也在创建这些按钮,所以我可以添加几个变量供以后使用

有没有人给我一个简单的答案?

谢谢马克

形式

Public Class Form1

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For n = 0 To 3
        Dim ctl As New item_button
        AddHandler ctl.Click, AddressOf Me.ClickMe
        ctl.Name = "btn" & n
        ctl.btn.Text = "Button " & n
        ctl.btnID = n
        ctl.Location = New Point(10, n * 50)
        Me.Controls.Add(ctl)
    Next
End Sub

Public Sub ClickMe(ByVal s As Object, ByVal e As EventArgs)
    'do something
    Dim btn As item_button
    btn = CType(s, item_button)

    TextBox1.Text = "Button " & s.btnID & " was pressed"
End Sub

End Class

ITEM_BUTTON

Public Class item_button

Public btnID As Integer
Public btnColor As System.Drawing.Color



Public Function ClickIt() As Integer
    Return btnID
End Function
End Class
4

2 回答 2

1

您的“按钮”不继承自Button

Public Class ItemButton  ' Naming-Conventions: http://msdn.microsoft.com/en-us/library/ms229040(v=vs.110).aspx
    Inherits Button

    Public Property BtnID As Integer
    Public Property BtnColor As System.Drawing.Color

    Public Function ClickIt() As Integer
        Return btnID
    End Function
End Class

由于我不确定您实际上要实现什么,因此我向您展示了一个示例,其中包含在自定义按钮中引发并以以下形式处理的自定义事件:

Public Class ItemButton
    Inherits Button

    Public Property BtnID As Integer
    Public Property BtnColor As System.Drawing.Color
    Public Event ButtonClicked(sender As ItemButton, buttonID As Int32)

    Private Sub clicked(sender As Object, e As EventArgs) Handles Me.Click
        RaiseEvent ButtonClicked(Me, BtnID)
    End Sub
End Class

形式:

 Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For n = 0 To 3
        Dim ctl As New ItemButton
        AddHandler ctl.ButtonClicked, AddressOf Me.ItemButtonClicked
        ctl.Name = "btn" & n
        ctl.Name = "Button " & n.ToString()
        ctl.btnID = n
        ctl.Location = New Point(10, n * 50)
        Me.Controls.Add(ctl)
    Next
End Sub

Public Sub ItemButtonClicked(ByVal btn As ItemButton, ByVal buttonID As Int32)
    TextBox1.Text = "Button " & buttonID & " was pressed"
End Sub
于 2013-10-25T08:16:10.523 回答
0

已排序

Private Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn.Click
    RaiseEvent ButtonClicked(Me, btnID)
End Sub

谢谢蒂姆,你的代码有帮助

于 2013-10-25T08:49:28.700 回答