2010-07-15 50 views

回答

2

更新:我只是意識到你可能一直在問與我在下面提供的相反:如何添加項目 a ComboBox a List<string>。如果是這樣的話,你總是可以做這樣的:

List<string> strList = new List<string>(); 
strList.AddRange(cbx.Items.Cast<object>().Select(x => x.ToString())); 

這裏的擴展方法我用:

public static class ControlHelper 
{ 
    public static void Populate<T>(this ComboBox comboBox, IEnumerable<T> items) 
    { 
     try 
     { 
      comboBox.BeginUpdate(); 
      foreach (T item in items) 
      { 
       comboBox.Items.Add(item); 
      } 
     } 
     finally 
     { 
      comboBox.EndUpdate(); 
     } 
    } 
} 

這使您可以填充ComboBox任何泛型集合,可以被列舉。看到它是多麼容易調用:

List<string> strList = new List<string> { "abc", "def", "ghi" }; 
cbx.Populate(strList); 

請注意,您也可以使這種方法不通用,因爲ComboBox.Items屬性是一個非通用型的(你可以將任何object添加到Items)。在這種情況下,Populate方法將接受簡單的IEnumerable而不是IEnumerable<T>