Generic Event Handler

TedN

Freshman
Joined
Sep 25, 2006
Messages
35
I have a form with a multitude of labels. I would like to code a generic event handler so that a click on any of the labels would fire a single event.

The following code was adapted from a search on this site.
I have set it up so that when a label is clicked the label name should be displayed in a message box.
For this test case I only have two labels (Label1, Label2) on a form.

The problem is that the message displayed is always "Label1" regardless as to whether I click on the form, Label1 or Label2.

Code:
Public Class Form1
    Inherits System.Windows.Forms.Form

    Dim ctl As Control

    Private Sub Form1_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load

        AddGenericClickHandler(Me, AddressOf Generic_Click)

    End Sub


    Sub Generic_Click(ByVal sender As Object, ByVal e As EventArgs)

        If TypeOf ctl Is Label Then
            MsgBox(ctl.Name)
        End If

    End Sub


    Private Sub AddGenericClickHandler(ByVal Parent As Control, _
    ByVal Handler As EventHandler)

        For Each ctl In Parent.Controls
            AddHandler ctl.Click, Handler
        Next

        AddHandler Parent.Click, Handler

    End Sub

End Class


Your help would be much appreciated.

Thanks,
Ted
 
Found the answer. I needed to use sender instead of ctl in the following lines of code.

Code:
If TypeOf sender Is Label Then
    MsgBox(sender.Name)
End If
 
Back
Top