refer to object via string?

Chaseshaw

Member
Joined
Apr 21, 2010
Messages
8
Programming Experience
Beginner
I have a label testlabel.
is there some way I can refer to it as:

dim t as string = "testlabel"
(something here referring to the OBJECT with the same name as the string).text = "mytext"

? I have 50 labels with text to change and would love to be able to:

for i = 1 to 50
dim t as string = "testlabel" & i
convertsomehow(t, label).text = "mytext"
next

so that this would change testlabel1, testlabel2, testlabel3, ... , testlabel50. anyone know how to do this?

thanks.
 
VB.NET:
For i As Integer = 1 To 50
    CType(Me.Controls("testlabel" & i.ToString(), Label).Text = "something"
Next
 
VB.NET:
For i As Integer = 1 To 50
    CType(Me.Controls("testlabel" & i.ToString(), Label).Text = "something"
Next

No need to cast if you're only accessing members of the Control class, which Text is.

Note that that code will only find controls on the form itself, not nested inside other containers. For that you'd have to use the Controls collection of those containers.
 
Back
Top