C# Help - Casting Question

  • Thread starter Thread starter Yoshi
  • Start date Start date
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
 
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?
 
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
 
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
 
Back
Top