如何将枚举types绑定到DropDownList?

如果我有以下枚举

public enum EmployeeType { Manager = 1, TeamLeader, Senior, Junior } 

我有DropDownList,我想要将此EmployeeType枚举绑定到DropDownList,有没有办法做到这一点?

如果你有DropDownList对象叫ddl你可以做到这一点如下

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

如果你想要枚举值返回select….

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

你可以使用lambdaexpression式

  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(); 

这是另一种方法:

 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); } 

我用这个链接来做到这一点:

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

我写了一个帮助函数给我一个我可以绑定的字典:

 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; }