C# Help - Casting Question

Y

Yoshi

Let's say that I have the following:

String name = "lblDescription";

The string assigned to the name variable is actually a label control on my
form with that name. Is there away in C# to the name and "cast" it to the
actual label control with that name?

Label l = (Label) name;

I know it doesn't work but can it be done?

Thanks,

Yosh
 
L

Lateralus [MCAD]

to my knowledge this can't be done. Maybe I'm not understanding your
question. Do you want to assign the "Text" of the label?
 
T

The Last Gunslinger

Yoshi said:
Let's say that I have the following:

String name = "lblDescription";

The string assigned to the name variable is actually a label control on my
form with that name. Is there away in C# to the name and "cast" it to the
actual label control with that name?

Label l = (Label) name;

I know it doesn't work but can it be done?

Thanks,

Yosh
You can iterate through the controls on your form, checking the name
each time to see if it matches your string.

ie
foreach(Control ctl in this.Controls)
{
if(ctl.Name == "LabelName")
{
MyLabel = (Label)ctl;
break;
}
}

HTH
JB
 
G

Guest

Hi Yoshi,

Your question is not very clear...:(

Are you trying to find out the control with the name as specified in the
'name' string variable?
Ans: Iterate thru the controls listed in the form's Controls
collection....for each of them check whether the name property is equal to
'name' string. If yes, cast it to a Label and do your implementation.

Or are you simply trying to assign the value of the variable 'name' to the
Label control 'l'?
Ans: l.Text = name

HTH,

- Rakesh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top