views:

304

answers:

3

Is there a way to change the property of an object in C# like this.

int Number = 1;

label[Number].Text = "Test";

And the result will change label1.Text to "Test";

Hope you understand what I mean.

+2  A: 

You may put all the labels into an array:

var labels = new[] { label1, label2, label3, label4 };

And then use array indexer:

int number = 0;
labels[number].Text = "Test";
Darin Dimitrov
Remember that in C# arrays are indexed from 0
Pawel Lesnikowski
+2  A: 

Add labels to a List

List<Label> list = new List<Label>()
list.Add(label1);
list.Add(label2);

list[0].Text = "Text for label 1";
list[1].Text = "Text for label 2";

Reflection is the another way, but most likely it's not what you meant.

Pawel Lesnikowski
A: 

Maybe dictionary (or associated array) can help you. Where key is integer and value - Label:

var dictionary = new Dictionary<int, Label>();
dictionary[2] = label1;
dictionary[7] = label2;
dictionary[12] = label2;

int number = 2;
dictionary[number].Text = "Test";
Sergey Teplyakov