Search code examples
vb.netwinformsevent-handlingtagsaddhandler

Dynamic label with Handler


I have labels that are dynamically added on to the form with each of them having a link under their tag. I also have the AddHandler lbTitle.Click to the dynamic labels, but when I try to do this, it doesn't work:

Private Sub lbTitle_Click(ByVal sender As Object, ByVal e As EventArgs)
    Process.Start(e.Tag)
End Sub

Because

'tag' is not a member of 'System.EventArgs'

How can I solve this so that when someone clicks on of the dynamically added labels, it would launch the url from the label's tag.


Solution

  • To add an event handler, you need the AddressOf Operator

    AddHandler lbTitle.Click, AddressOf lbTitle_Click 
    

    To get the reference to your Label in the event handler, you can use the sender argument:

    Private Sub lbTitle_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim label = DirectCast(sender, Label)
        Process.Start(label.Tag.ToString())
    End Sub