Monday, March 28, 2011

Common Event Handlers in VB.NET

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
From stackoverflow
  • In VB.Net, "Me" is the equivalent to C#'s "this".

  • I think you want the "Me" keyword.

  • 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
    
    Sam Meldrum : My thoughts exactly
    R. Bemrose : It makes me wonder why sender isn't declared as a control in .NET... I suppose because the sender could also be a Form or something.
    Konrad Rudolph : R. Bemrose: because this general method signature for event handlers isn't only used for Control events! In fact, it should be used for *all* events. Past versions of .NET required a common signature for lack of contravariant delegates. This is no longer true in the current versions of VB and C#.
  • Yes man, in VB.NET "this." is referred as "me."

    and solution for ur 2nd q regarding handlers for VB.NET is, u can add handles at the end of 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

0 comments:

Post a Comment