Is there a way to detect when a label is clicked without doing on click events for all the labels? I want to be able to detect the click, find what has been clicked, then I can change the label since I'll know which one has been clicked.
Public Sub LabelClickEvent(byval sender as object, byval e as EventArgs) Handles label1.Click, label4.Click, label9.Click
Select Case DirectCast(sender, Label).Name.ToUpper()
'Process for different label names
Case "LABEL1":
' Alternatively you could use the tag to store information and then process based on that in the select
End Select
End Sub
For Each ctr As Control In Me.Controls
If TypeOf ctr Is Label Then
Dim lb As Label = CType(ctr, Label)
Addhandler lb.Click, Addressof LabelClickEvent
Next ctr
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each ctrl As Control In Me.Controls
If TypeOf ctrl Is Label Then
AddHandler ctrl.Click, AddressOf label_Click
End If
Next
End Sub
Private Sub label_Click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show(CType(sender, Label).Name & " clicked")
End Sub
For Each lbl As Control In Me.Controls
If TypeOf lbl Is Label Then AddHandler(yourSubRoutine, Ctype(lbl, Label))
Next
Is it possible to have it handle all labels or all controls? I want to avoid coding the specific names and instead let the function detect what it is.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each ctrl As Control In Me.Controls
AddHandler ctrl.Click, AddressOf ctrl_Click
Next
End Sub
Private Sub ctrl_Click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show(String.Format("Type of control: {0}{1}Name of control: {2}", sender.GetType, Environment.NewLine, sender.Name))
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddClickHandlers(Me.Controls)
End Sub
Private Sub AddClickHandlers(ByVal ctrlColl As System.Windows.Forms.Form.ControlCollection)
For Each ctrl As Control In ctrlColl
AddHandler ctrl.Click, AddressOf ctrl_Click
If ctrl.HasChildren Then
AddClickHandlers(ctrl.Controls)
End If
Next
End Sub
Private Sub AddClickHandlers(ByVal ctrlColl As System.Windows.Forms.Control.ControlCollection)
For Each ctrl As Control In ctrlColl
AddHandler ctrl.Click, AddressOf ctrl_Click
If ctrl.HasChildren Then
AddClickHandlers(ctrl.Controls)
End If
Next
End Sub
Private Sub ctrl_Click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show(String.Format("Type of control: {0}{1}Name of control: {2}", sender.GetType, Environment.NewLine, sender.Name))
End Sub