3

I have a several labels all coded as such:

Public assessment_menu_button As New Label
Public current_label_clicked As New Label

AddHandler assessment_menu_button.Click, AddressOf click_assessment_menu_button

Private Sub click_assessment_menu_button(ByVal sender As System.Object, 
                                         ByVal e As System.EventArgs)
   current_label_clicked = sender
   ' do some other stuff
End Sub

Then, later in my program, I have a Sub which needs to perform a click on whichever label was put into current_label_clicked and raise a click event on it. Something like

Private Sub whatever()
    current_label_clicked.performClick()
End Sub

but you can't do that with labels.

So how do I raise the click event for the label?

Thanks.

John
  • 1,310
  • 3
  • 32
  • 58

2 Answers2

5

Let's say your label is named Label1.

This Sub is the Sub that will be executed when you click on the label.

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click

End Sub

To raise a label click, you just need to call that event.

Label1_Click(Label1, Nothing)

That's it :)

  • Thanks for the info, but I have several buttons and I do not want a separate function for each button. I am trying to use a single function for all labels and a single variable to reference the one that was clicked. When the "click" subroutine is called, just use whatever label is referenced by the variable and perform a click event for it. – John Aug 27 '13 at 14:30
  • This would work if I could use "...) Handles sender.Click", but that gives me an error. – John Aug 27 '13 at 14:33
  • If you have 3 labels name Label1, Label2 and Label3 you can create a Function that handles click on all these labels. ` Private Sub Label_Click(sender As Object, e As EventArgs) Handles Label1.Click, Label2.Click, Label3.Click 'something here End Sub` – William Gérald Blondel Aug 27 '13 at 14:36
  • 1
    OK, I figured it out. I can simply leave off the "Handles" statement and it works just as well. – John Aug 27 '13 at 14:43
  • Apparently, I need to wait 8 hours to post my final code as an answer, but basically I changed my calling routing to be the same as yours (William), but using my own naming convention. – John Aug 27 '13 at 14:48
1

It's considered bad form to call the event handler method directly. Put the code you need to call when the label is clicked into a method and call that method from both the label click handler and the whatever method:

Private Sub click_assessment_menu_button(ByVal sender As System.Object, ByVal e As System.EventArgs)
    runLabelCode(sender)

    'other code here
End Sub

Private Sub runLabelCode(sender As Label)
    current_label_clicked = sender

    'other code here
End Sub

'elsewhere in the code
Private Sub Whatever()
    runLabelCode(Label1, Nothing)
End Sub
Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48