开发者

C# change property of an object dynamically

开发者 https://www.devze.com 2022-12-17 02:43 出处:网络
Is there a way to change the property of an object in C# like this. int Number = 1; label[Number].Text = \"Test\";

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 wil开发者_如何学Gol change label1.Text to "Test";

Hope you understand what I mean.


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";


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.


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";


Try FindControl:

Label lbl = (Label) FindControl("label" + yourVariableHere);
lbl.Text = "Test";

http://msdn.microsoft.com/en-us/library/486wc64h.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消