Search code examples
vb.netvariablesprivatepublic

in vb.net how do I declare a public variable from a private sub


I am creating Labels dynamically from a private sub, and I want to be able to do something when the user clicks on them. However, I can't use "Dim withEvents blah..." because it says withEvents can't be used on a local variable but I also can't use "Public withEvents blah" from within my Private Sub. How do I accomplish this?

Thanks.


Solution

  • When you create dynamic control, you can add a handler for it

    Dim mylbl As New Label
    mylbl.Name = "button1"
    mylbl.Text = "hi"
    Me.Controls.Add(mylbl)
    
    AddHandler lbl.Click, AddressOf AllLabels_Click
    

    This is your Handler Sub

    Sub AllLabels_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    
        Dim lbl As Label = CType(sender, Label)
    
        MsgBox(lbl.Text)
    
    End Sub