2010-06-23 49 views

回答

65

,如果你有一個名爲DropDownList的對象的DDL,你可以做到這一點,如下

ddl.DataSource = Enum.GetNames(typeof(EmployeeType)); 
ddl.DataBind(); 

,如果你想枚舉值回選擇....

EmployeeType empType = (EmployeeType)Enum.Parse(typeof(EmployeeType), ddl.SelectedValue); 
1

我寫了一個輔助函數給我一本我可以綁定的字典:

public static Dictionary<int, string> GetDictionaryFromEnum<T>() 
{ 

    string[] names = Enum.GetNames(typeof(T)); 

    Array keysTemp = Enum.GetValues(typeof(T)); 
    dynamic keys = keysTemp.Cast<int>(); 

    dynamic dictionary = keys.Zip(names, (k, v) => new { 
     Key = k, 
     Value = v 
    }).ToDictionary(x => x.Key, x => x.Value); 

    return dictionary; 
} 
12

你可以使用lambda表達式

 ddl.DataSource = Enum.GetNames(typeof(EmployeeType)). 
     Select(o => new {Text = o, Value = (byte)(Enum.Parse(typeof(EmployeeType),o))}); 
     ddl.DataTextField = "Text"; 
     ddl.DataValueField = "Value"; 
     ddl.DataBind(); 

或LINQ

 ddl.DataSource = from Filters n in Enum.GetValues(typeof(EmployeeType)) 
       select new { Text = n, Value = Convert.ToByte(n) }; 
     ddl.DataTextField = "Text"; 
     ddl.DataValueField = "Value"; 
     ddl.DataBind(); 
+0

輕微錯字在lambda表達式示例(錯過了一個結束捲曲托架)。 ddl.DataSource = Enum.GetNames(typeof(EmployeeType))。 Select(o => new {Text = o,Value =(byte)(Enum.Parse(typeof(EmployeeType),o))}); – wloescher 2015-04-30 21:05:06