Mark Cooney
Mark Cooney

Reputation: 121

Dynamic UserControl AddHandler

I am trying to understand why my AddHandler isn't working.

I have found a workaround if buttons always on same form but they may not be in the future.

I am also creating these buttons so I can add several variables for later use

Any have a simple answer for me please?

Thanks Mark

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

Upvotes: 0

Views: 1926

Answers (2)

Mark Cooney
Mark Cooney

Reputation: 121

Sorted

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

Thanks Tim, your code helped

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

Your "Button" does not inherit from 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

Since i'm not sure what you're actually trying to achieve i show you an example with a custom event that is raised in the custom button and handled in the form:

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

in the form:

 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

Upvotes: 1

Related Questions