2010-06-23 23 views

Trả lời

65

nếu bạn có DropDownList đối tượng gọi là DDL bạn có thể làm điều đó như sau

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

nếu bạn muốn giá trị Enum Quay trở lại Selection ....

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

tôi đã viết một hàm helper để cho tôi một từ điển mà tôi có thể ràng buộc:

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

bạn có thể sử dụng biểu thức 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(); 

hoặc 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

typo nhẹ trong lambda dụ biểu (thiếu một dấu đóng dấu ngoặc). ddl.DataSource = Enum.GetNames (typeof (EmployeeType)). Chọn (o => new {Văn bản = o, Giá trị = (byte) (Enum.Parse (typeof (EmployeeType), o))}); – wloescher

4

Đây là cách tiếp cận khác:

Array itemNames = System.Enum.GetNames(typeof(EmployeeType)); 
foreach (String name in itemNames) 
{ 
    //get the enum item value 
    Int32 value = (Int32)Enum.Parse(typeof(EmployeeType), name); 
    ListItem listItem = new ListItem(name, value.ToString()); 
    ddlEnumBind.Items.Add(listItem); 
} 

tôi được sử dụng liên kết này để làm điều đó:

http://www.codeproject.com/Tips/303564/Binding-DropDownList-Using-List-Collection-Enum-an

Các vấn đề liên quan