动态UserControl AddHandler

时间:2013-10-25 08:10:34

标签: vb.net addhandler

我想了解为什么我的AddHandler无法正常工作。

如果按钮始终位于相同的表单上,但我们找到了一种解决方法,但它们可能不会在将来使用。

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

请给我一个简单的答案吗?

由于 标记

FORM

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

排序

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

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