Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

 

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

Posted

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

 

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...