如何将枚举类型绑定到DropDownList?

Hot*_*oil 37 c# asp.net enums

如果我有以下枚举

public enum EmployeeType
{
    Manager = 1,
    TeamLeader,
    Senior,
    Junior
}
Run Code Online (Sandbox Code Playgroud)

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

Amr*_*awy 70

如果你有一个名为ddl的DropDownList对象,你可以这样做

ddl.DataSource = Enum.GetNames(typeof(EmployeeType));
ddl.DataBind();
Run Code Online (Sandbox Code Playgroud)

如果你想要Enum值返回选择....

 EmployeeType empType = (EmployeeType)Enum.Parse(typeof(EmployeeType), ddl.SelectedValue);
Run Code Online (Sandbox Code Playgroud)


ni3*_*net 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();
Run Code Online (Sandbox Code Playgroud)

或者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();
Run Code Online (Sandbox Code Playgroud)


San*_*rta 5

这是另一种方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

我用这个链接做到了:

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