Ofir Baruch
Ofir Baruch

Reputation: 10346

VB 2010 - A variable with a value of a label name

I'm using VB 2010 Express and have a label named "lblTitle" in my form. The next code doesn't work and I know it , but how can I do something like this?

Dim bla As String
bla = "lblTitle"
bla.Text = "Hello world"

Edit: I want to access a label properties without actually having its name. I get its name from a text file.

Edit 2: Thanks you all guys! After googling this function you've mentioned I got it:

   Dim bla = "lblName"
   Me.Controls(bla).Text = "Dan"

While "lblName" is a label's name in the form.

Upvotes: 2

Views: 10752

Answers (5)

Wingman4l7
Wingman4l7

Reputation: 678

Seems like the best way to do this is to make a string representing the name of the control, then cast it as a control. This saves you having to make a variable, as well. Your method might appear to work, but I'm not sure it wouldn't fail once you run it. Also, it would throw an error in the IDE if you were trying to access a property more specific to the type of control, and not something common like Text. See my closely related question:

accessing multiple form controls using a variable for the name

Upvotes: 0

Ofir Baruch
Ofir Baruch

Reputation: 10346

After a deep google search , the answer seems to be easy as that:

   Dim bla = "lblName"
   Me.Controls(bla).Text = "Dan"

while lblName is the label's name in the form. Thanks guys

Upvotes: 1

JonAlb
JonAlb

Reputation: 1720

DirectCast(Page.FindControl("lblTitle"), Label).Text = "some new value"

Upvotes: 0

Carlos Quintanilla
Carlos Quintanilla

Reputation: 13343

You can do this assuming you are using windows forms:

DirectCast(Me.Controls.Find("lblTitle", True)(0), Label).Text = "Hello world"

Upvotes: 0

p.campbell
p.campbell

Reputation: 100667

Try this:

Dim myLabel As Label = DirectCast(Page.FindControl("lblTitle"), Label)
myLabel.Text = "some new value"

Upvotes: 1

Related Questions