I have n Labels on Form, e.g: Label1, Label2,..., Labeln. Normally, when I write Click event for all Labels:
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
Msgbox "1"
End Sub
Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label2.Click
Msgbox "2"
End Sub
Private Sub Labeln_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Labeln.Click
Msgbox "n"
End Sub
Writting is very complex when n is large!
Now, I want to write the code simply to click to Lablei and generate "i" (one proceduce to many proceduces). How to handle it? Thanks in advance.
Private Sub Labeln_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Label1.Click, Label2.Click, Label3.Click '...
Dim l As Label = DirectCast(sender, Label)
Msgbox l.Name
End Sub
If n is very large, skip the Handles portion of the method and do this in your form load:
For Each l As Label in Me.Controls.OfType(Of Label)()
AddHandler l.Click, AddressOf Labeln_Click
Next
You can dynamically assign the event handlers when you create your labels using AddHandler:
Sub test()
Dim label1 As New Label()
AddHandler label1.Click, AddressOf HandleLabelClick
Me.Controls.Add(label1)
End Sub
Here's the event handler:
Sub HandleLabelClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
MsgBox(DirectCast(sender, Label).Name)
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With