Reputation: 51
I am trying to loop trough something 3 times and change the .text property of 3 element that have the names "label1", "label2" and "label3". I'm trying to add the 1,2,3 to the label but I can't get it to work.
this is what I'm trying to do: the y is either 1,2 or 3
("label" + y).Text
Upvotes: 0
Views: 314
Reputation: 736
I think you want this,so I make a simple code of it.
for(int i = 1; i <= 3; i++)
{
Console.WriteLine("label" + i);
}
Upvotes: 1
Reputation: 169
if I understand correctly - you can do this using reflection:
var temp = (double)typeof(MyClass).GetProperty("label" + y).GetValue(myClassInstance);
if you change the type of MyClass
to the class that holds your variable, myClassInstance
to an instance of your class and the cast from double to your field type (which I'm guessing is some sort of WPF / Winforms control) you can get the variable by name.
It's important to note that your program will slow down if this is used often.
Upvotes: 1