Question How to use AddHandler?

fredfrothen

New member
Joined
Apr 16, 2013
Messages
4
Programming Experience
Beginner
Hey i posted the other day asking how to handle a dynamically loaded button's click event, which i got the answer of use Addhandler. I've been trying to use it for awhile but can't seem to get it to work as i need.
I've managed to capture the button click, but where i have my message box saying "Button Clicked" i need to display the caption of the button clicked, but i can't seem to add brackets to the addhandler statement.

Here's my code:
VB.NET:
    Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        PopulateWorlds()

    End Sub


    Private Sub PopulateWorlds()

        Dim intCount As Integer

        For intCount = 1 To 78

            Dim cbDynBut As New CovButton
            Me.fraRight1.Controls.Add(cbDynBut)
            cbDynBut.Name = "cbWorld" & intCount
            cbDynBut.Caption = "W " & intCount
            cbDynBut.Width = 50
            cbDynBut.Height = 16

            If intCount <= 20 Then
                cbDynBut.Left = 7
                cbDynBut.Top = 66 + (20 * (intCount - 1))
            ElseIf intCount > 20 And intCount <= 40 Then
                cbDynBut.Left = 63
                cbDynBut.Top = 66 + (20 * ((intCount - 1) - 20))
            ElseIf intCount > 40 And intCount <= 60 Then
                cbDynBut.Left = 119
                cbDynBut.Top = 66 + (20 * ((intCount - 1) - 40))
            Else
                cbDynBut.Left = 175
                cbDynBut.Top = 66 + (20 * ((intCount - 1) - 60))
            End If

            AddHandler cbDynBut.Click, AddressOf HandleDynButton

        Next intCount

    End Sub

    Sub HandleDynButton()
        MsgBox("Button clicked")
    End Sub
 
Last edited:
Your AddHandler statement is exactly right as it is. It's your event handler method that is wrong. What does an event handler usually look like? Here's a clue from your own code:
VB.NET:
    Private Sub frmMain_Load([B][U]sender As System.Object, e As System.EventArgs[/U][/B]) Handles MyBase.Load

        PopulateWorlds()

    End Sub
All events in the .NET Framework provide two arguments to their handlers: 'sender' and 'e', which are the object that raised the event and the data for the event respectively. The Click event of a Button is no different. You just haven't provided the parameters in your event handler to receive those arguments so you can't use them. Try adding a Button in the designer and creating a Click event handler and see what it looks like. That's what you have to change. To learn more about where those two arguments come from and what they can be used for, follow the Blog link in my signature and check out my post on Custom Events. As I said, the 'sender' is the object that raised the event. In this case, that means the Button that was clicked, so that's obviously where you would get the Text of the Button from.
 
Back
Top