有沒有辦法像這樣在C#中更改對象的屬性。C#動態更改對象的屬性
int Number = 1;
label [Number] .Text =「Test」;
並且結果會將label1.Text更改爲「Test」;
希望你明白我的意思。
有沒有辦法像這樣在C#中更改對象的屬性。C#動態更改對象的屬性
int Number = 1;
label [Number] .Text =「Test」;
並且結果會將label1.Text更改爲「Test」;
希望你明白我的意思。
你可以把所有的標籤到一個數組:
var labels = new[] { label1, label2, label3, label4 };
然後使用數組索引:
int number = 0;
labels[number].Text = "Test";
標籤添加到列表
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是另一方式,但很可能這不是你的意思。
也許字典(或關聯數組)可以幫助你。其中,key是整數和價值 - 標籤:
var dictionary = new Dictionary<int, Label>();
dictionary[2] = label1;
dictionary[7] = label2;
dictionary[12] = label2;
int number = 2;
dictionary[number].Text = "Test";
嘗試的FindControl:
Label lbl = (Label) FindControl("label" + yourVariableHere);
lbl.Text = "Test";
請記住,在C#數組索引從0 – 2010-01-23 11:16:39