0

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.

user2018388
  • 31
  • 2
  • 10

1 Answers1

2

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
matzone
  • 5,703
  • 3
  • 17
  • 20
  • That does not work for private variables. If you want to add an eventhandler to a control, the control must be created using "withEvents" which can only be done on Public variables. – user2018388 Jun 15 '13 at 02:20
  • By "variables" I mean dynamically created controls. – user2018388 Jun 15 '13 at 02:20
  • @user2018388, Public vs private is how they are accessed not how they are wired to events! – OneFineDay Jun 15 '13 at 02:37
  • @user2018388, all dynamically added control must have handlers added the way matzone showed. – OneFineDay Jun 15 '13 at 02:39
  • @user2018388, it sounds like you're having a problem with your handler's definition. Note that in this example there is no `Handles` keyword after `Sub AllLabels_Click(ByVal sender As Object, ByVal e As System.EventArgs)`. – Kirill Shlenskiy Jun 15 '13 at 02:41
  • "WithEvents" only works with one control anyways (whatever was last assigned to the WithEvents variable). AddHandler is definitely the way to go. This is not a "private" variable, it is a "local" variable. This local variable does NOT go out of scope when the sub exits because not only does the form have a reference to it in its Controls() collection, but there is also a reference to it via the wired handler. – Idle_Mind Jun 15 '13 at 03:53
  • OK, I now see how it works. The "handles" thing was throwing me off. Thanks Matzone. – user2018388 Jun 19 '13 at 13:42
  • How do I mark this as answered? I clicked on the green check mark, but it still says "unanswered" – user2018388 Jun 19 '13 at 13:44
  • @user2018388 .. it's OK just make a green check ! thanx ! – matzone Jun 19 '13 at 13:45