Common Event Handlers in VB.NET
-
21-08-2019 - |
Question
I have around 10 buttons on my form and I want them to call the same Click event handler.
But for that I need the Event handler to be generalized and we don't have "this" keyword in VB.NET to refer to the control that caused the event.
How do I implement the functionality of "this" keyword in VB.NET?
I want to be able to write an Event handler that does the following:
Private Sub cmdButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdButton1.Click
currentTag = this.Tag
End Sub
Solution
How do I implement the functionality of "this" keyword in VB.NET?
this
is called Me
in VB. However, this has got nothing to do with your code and refers to the containing class, in your case most probably the current Form
. You need to access the sender
object parameter, after casting it to Control
:
currentTag = DirectCast(sender, Control).Tag
OTHER TIPS
In VB.NET, Me
is the equivalent to C#'s this
.
I think you want the Me
keyword.
In VB.NET this
is referred as me
, and the solution for your second question regarding handlers for VB.NET is: You can add Handles
at the end of a Private Sub
statement, like:
Private Sub cmdButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles cmdButton1.Click, 'cmdButton2.click, cmdButton3.click'
currentTag = this.Tag
End Sub