soxroxr
soxroxr

Reputation: 307

VB.Net - How do you "dynamically" select an object?

I'm not sure if the question properly asks what I want, because I'm a bit new, but what I am trying to do is write a sub or function that I can run when a label is clicked, and I want to to be reusable on multiple labels. There will be 12 in total, and I don't wish to write the same thing over and over, with slightly different characters. A programmer never wants to write the same thing twice, right? Also, something else is making it a necessity to do it dynamically.

So, how I was trying to accomplish that was by using a string, and adding the name of the label to the string on click.

 click1 = "Label1"

As it turns out, you can't just say click1.Text and return the text of Label1. The reason it's important to do it implicitly is because I need to somehow remember the one I clicked before, to compare the first click and second click, and if they match, do A, and if they don't match, do B.

Upvotes: 0

Views: 415

Answers (2)

bendataclear
bendataclear

Reputation: 3848

mfeingold is correct, if you're unsure of the syntax:

Private Sub LabelClicked (ByVal sender As Object, ByVal e As EventArgs) Handles Label1.Click, Label2.Click, Label3.Click
    sender.Text = "I've been clicked."
End Sub

Upvotes: 1

mfeingold
mfeingold

Reputation: 7134

The first parameter (it is called sender) to the event handler your wrote to respond to the click event is the object which sent the event.

If you assign the same routine to respond to on click of all your labels, it will be called for every one of them, but the sender parameter will point to the actual label which was clicked

HTH

Upvotes: 3

Related Questions