2012-09-16 133 views
0

到組合框我有一個列表添加項列表

List<Control> inputBoxes = new List<Control>(); 

在那裏我已經添加組合框和文本框。

我可以使用inputBoxes[0].GetType().GetProperty("Text").SetValue(inputBoxes[0], "ABC", null); 設置文本屬性,但是如何將項目添加到組合框並選擇它們?

能以某種方式使用inputBoxes[0].GetType().GetMethod()嗎?

+1

爲什麼不只是'添加(..)',爲什麼要使用反射? – Tigran

回答

0

爲什麼使用反射來簡單地設置屬性?

您可以使用此這是更有效和更容易出錯:

inputBoxes.OfType<TextBox>().ElementAt(0).Text = "ABC"; 

如果你想將項目添加到一個(或多個)組合框:

var combos = inputBoxes.OfType<ComboBox>(); 
foreach(ComboBox combo in combos) 
{ 
    // add items here or set their DataDource, for example: 
    string[] installs = new string[]{"Typical", "Compact", "Custom"}; 
    combo.Items.AddRange(installs); 
} 

請注意,您需要爲OfType添加using System.Linq

+0

謝謝!它現在有效。 – user1070134