如何将枚举绑定到ASP.NET中的下拉列表控件?

时间:2021-04-05 20:54:26

Let's say I have the following simple enum:

假设我有以下简单的enum:

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?

如何将此枚举绑定到DropDownList控件,以便在列表中显示描述,并在选择选项后检索相关的数值(1,2,3)?

24 个解决方案

#1


104  

I probably wouldn't bind the data as it's an enum, and it won't change after compile time (unless I'm having one of those stoopid moments).

我可能不会绑定数据,因为它是enum,而且在编译时之后它也不会更改(除非我有一个stoopid时刻)。

Better just to iterate through the enum:

最好是在enum中迭代:

Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next

Or the same in C#

c#也是一样

Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(item);
}

#2


68  

Use the following utility class Enumeration to get an IDictionary<int,string> (Enum value & name pair) from an Enumeration; you then bind the IDictionary to a bindable Control.

使用以下实用工具类枚举从枚举中获取IDictionary (Enum值& name对);然后将IDictionary绑定到可绑定控件。 ,字符串>

public static class Enumeration
{
    public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct
    {
        var enumerationType = typeof (TEnum);

        if (!enumerationType.IsEnum)
            throw new ArgumentException("Enumeration type is expected.");

        var dictionary = new Dictionary<int, string>();

        foreach (int value in Enum.GetValues(enumerationType))
        {
            var name = Enum.GetName(enumerationType, value);
            dictionary.Add(value, name);
        }

        return dictionary;
    }
}

Example: Using the utility class to bind enumeration data to a control

示例:使用实用程序类将枚举数据绑定到控件

ddlResponse.DataSource = Enumeration.GetAll<Response>();
ddlResponse.DataTextField = "Value";
ddlResponse.DataValueField = "Key";
ddlResponse.DataBind();

#3


36  

I use this for ASP.NET MVC:

我用这个来表示ASP。NET MVC:

Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast<enumtype>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

#4


35  

My version is just a compressed form of the above:

我的版本只是上面的压缩格式:

foreach (Response r in Enum.GetValues(typeof(Response)))
{
    ListItem item = new ListItem(Enum.GetName(typeof(Response), r), r.ToString());
    DropDownList1.Items.Add(item);
}

#5


21  

public enum Color
{
    RED,
    GREEN,
    BLUE
}

Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:

每个Enum类型都来自System.Enum。有两个静态方法可以帮助将数据绑定到下拉列表控件(并检索值)。这些是枚举。getname Enum.Parse。使用GetNames,您可以绑定到下拉列表控件,如下所示:

protected System.Web.UI.WebControls.DropDownList ddColor;

private void Page_Load(object sender, System.EventArgs e)
{
     if(!IsPostBack)
     {
        ddColor.DataSource = Enum.GetNames(typeof(Color));
        ddColor.DataBind();
     }
}

Now if you want the Enum value Back on Selection ....

现在,如果你想要枚举值重新选择....

  private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   Color selectedColor = (Color)Enum.Parse(ddColor.SelectedValue); 
  }

#6


9  

After reading all posts I came up with a comprehensive solution to support showing enum description in dropdown list as well as selecting proper value from Model in dropdown when displaying in Edit mode:

在阅读了所有的文章后,我提出了一个全面的解决方案,在下拉列表中显示enum description,并在编辑模式下显示时从下拉列表中选择适当的值:

enum:

枚举:

using System.ComponentModel;
public enum CompanyType
{
    [Description("")]
    Null = 1,

    [Description("Supplier")]
    Supplier = 2,

    [Description("Customer")]
    Customer = 3
}

enum extension class:

enum扩展类:

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;

public static class EnumExtension
{
    public static string ToDescription(this System.Enum value)
    {
        var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }

    public static IEnumerable<SelectListItem> ToSelectList<T>(this System.Enum enumValue)
    {
        return
            System.Enum.GetValues(enumValue.GetType()).Cast<T>()
                  .Select(
                      x =>
                      new SelectListItem
                          {
                              Text = ((System.Enum)(object) x).ToDescription(),
                              Value = x.ToString(),
                              Selected = (enumValue.Equals(x))
                          });
    }
}

Model class:

模型类:

public class Company
{
    public string CompanyName { get; set; }
    public CompanyType Type { get; set; }
}

and View:

和观点:

@Html.DropDownListFor(m => m.Type,
@Model.Type.ToSelectList<CompanyType>())

and if you are using that dropdown without binding to Model, you can use this instead:

如果你使用下拉菜单而不与模型绑定,你可以使用这个:

@Html.DropDownList("type",                  
Enum.GetValues(typeof(CompanyType)).Cast<CompanyType>()
.Select(x => new SelectListItem {Text = x.ToDescription(), Value = x.ToString()}))

So by doing so you can expect your dropdown displays Description instead of enum values. Also when it comes to Edit, your model will be updated by dropdown selected value after posting page.

因此,通过这样做,您可以期望您的下拉显示描述而不是枚举值。另外,当需要编辑时,您的模型将在发布页面后通过下拉选择值进行更新。

#7


8  

As others have already said - don't databind to an enum, unless you need to bind to different enums depending on situation. There are several ways to do this, a couple of examples below.

正如其他人已经说过的那样——不要将数据库绑定到enum,除非您需要根据情况绑定到不同的enum。有几种方法可以做到这一点,下面有几个例子。

ObjectDataSource

ObjectDataSource来

A declarative way of doing it with ObjectDataSource. First, create a BusinessObject class that will return the List to bind the DropDownList to:

使用ObjectDataSource实现此操作的声明式方法。首先,创建一个BusinessObject类,该类返回列表,将下拉列表绑定到:

public class DropDownData
{
    enum Responses { Yes = 1, No = 2, Maybe = 3 }

    public String Text { get; set; }
    public int Value { get; set; }

    public List<DropDownData> GetList()
    {
        var items = new List<DropDownData>();
        foreach (int value in Enum.GetValues(typeof(Responses)))
        {
            items.Add(new DropDownData
                          {
                              Text = Enum.GetName(typeof (Responses), value),
                              Value = value
                          });
        }
        return items;
    }
}

Then add some HTML markup to the ASPX page to point to this BO class:

然后向ASPX页面添加一些HTML标记,指向这个BO类:

<asp:DropDownList ID="DropDownList1" runat="server" 
    DataSourceID="ObjectDataSource1" DataTextField="Text" DataValueField="Value">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    SelectMethod="GetList" TypeName="DropDownData"></asp:ObjectDataSource>

This option requires no code behind.

此选项不需要后面的代码。

Code Behind DataBind

DataBind背后的代码

To minimize the HTML in the ASPX page and do bind in Code Behind:

为了最小化ASPX页面中的HTML并在后面绑定代码:

enum Responses { Yes = 1, No = 2, Maybe = 3 }

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        foreach (int value in Enum.GetValues(typeof(Responses)))
        {
            DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(Responses), value), value.ToString()));
        }
    }
}

Anyway, the trick is to let the Enum type methods of GetValues, GetNames etc. to do work for you.

总之,诀窍是让GetValues、GetNames等枚举类型方法为您工作。

#8


6  

I am not sure how to do it in ASP.NET but check out this post... it might help?

我不知道在ASP中怎么做。但看看这篇文章……它可能帮助吗?

Enum.GetValues(typeof(Response));

#9


5  

Array itemValues = Enum.GetValues(typeof(TaskStatus));
Array itemNames = Enum.GetNames(typeof(TaskStatus));

for (int i = 0; i <= itemNames.Length; i++)
{
    ListItem item = new ListItem(itemNames.GetValue(i).ToString(),
    itemValues.GetValue(i).ToString());
    ddlStatus.Items.Add(item);
}

#10


4  

public enum Color
{
    RED,
    GREEN,
    BLUE
}

ddColor.DataSource = Enum.GetNames(typeof(Color));
ddColor.DataBind();

#11


4  

You could use linq:

您可以使用linq:

var responseTypes= Enum.GetNames(typeof(Response)).Select(x => new { text = x, value = (int)Enum.Parse(typeof(Response), x) });
    DropDownList.DataSource = responseTypes;
    DropDownList.DataTextField = "text";
    DropDownList.DataValueField = "value";
    DropDownList.DataBind();

#12


3  

Generic Code Using Answer six.

使用回答6的通用代码。

public static void BindControlToEnum(DataBoundControl ControlToBind, Type type)
{
    //ListControl

    if (type == null)
        throw new ArgumentNullException("type");
    else if (ControlToBind==null )
        throw new ArgumentNullException("ControlToBind");
    if (!type.IsEnum)
        throw new ArgumentException("Only enumeration type is expected.");

    Dictionary<int, string> pairs = new Dictionary<int, string>();

    foreach (int i in Enum.GetValues(type))
    {
        pairs.Add(i, Enum.GetName(type, i));
    }
    ControlToBind.DataSource = pairs;
    ListControl lstControl = ControlToBind as ListControl;
    if (lstControl != null)
    {
        lstControl.DataTextField = "Value";
        lstControl.DataValueField = "Key";
    }
    ControlToBind.DataBind();

}

#13


3  

After finding this answer I came up with what I think is a better (at least more elegant) way of doing this, thought I'd come back and share it here.

在找到这个答案后,我想出了一个更好的方法(至少更优雅),我想我会回来分享它。

Page_Load:

Page_Load:

DropDownList1.DataSource = Enum.GetValues(typeof(Response));
DropDownList1.DataBind();

LoadValues:

LoadValues:

Response rIn = Response.Maybe;
DropDownList1.Text = rIn.ToString();

SaveValues:

SaveValues:

Response rOut = (Response) Enum.Parse(typeof(Response), DropDownList1.Text);

#14


1  

That's not quite what you're looking for, but might help:

这不是你想要的,但可能会有所帮助:

http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

#15


1  

Why not use like this to be able pass every listControle :

为什么不用这样可以通过每个列表:


public static void BindToEnum(Type enumType, ListControl lc)
        {
            // get the names from the enumeration
            string[] names = Enum.GetNames(enumType);
            // get the values from the enumeration
            Array values = Enum.GetValues(enumType);
            // turn it into a hash table
            Hashtable ht = new Hashtable();
            for (int i = 0; i < names.Length; i++)
                // note the cast to integer here is important
                // otherwise we'll just get the enum string back again
                ht.Add(names[i], (int)values.GetValue(i));
            // return the dictionary to be bound to
            lc.DataSource = ht;
            lc.DataTextField = "Key";
            lc.DataValueField = "Value";
            lc.DataBind();
        }
And use is just as simple as :

BindToEnum(typeof(NewsType), DropDownList1);
BindToEnum(typeof(NewsType), CheckBoxList1);
BindToEnum(typeof(NewsType), RadoBuuttonList1);

#16


0  

This is my solution for Order an Enum and DataBind(Text and Value)to Dropdown using LINQ

这是我的解决方案,可以使用LINQ命令下拉Enum和DataBind(文本和值)

var mylist = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList<MyEnum>().OrderBy(l => l.ToString());
foreach (MyEnum item in mylist)
    ddlDivisao.Items.Add(new ListItem(item.ToString(), ((int)item).ToString()));

#17


0  

For some reason the answer provided by Mark Glorie didn't work for me. As the GetValues return an Array object and I couldn't use indexer to gets its items value. I tried itemsValue.GetValue(i) and it worked but unfortunately, it didn't populate the enum value to the dropdownlist item's value. It just populated enum item name as the text and value of the dropdownlist.

由于某种原因,马克·格洛里提供的答案对我不起作用。当GetValues返回一个数组对象时,我不能使用indexer获取它的items值。我尝试了itemsValue.GetValue(I),但不幸的是,它没有将enum项的值填充到enum值中。它只是填充枚举项名称作为下拉列表的文本和值。

I modified Mark's code further and have posted it as the solution here How to bind an Enum with its value to the DropDownList in ASP.NET?

我进一步修改了Mark的代码,并将其作为解决方案发布在这里,如何将枚举值绑定到ASP.NET中的下拉列表?

Hope this helps.

希望这个有帮助。

Thanks

谢谢

#18


0  

Check out my post on creating a custom helper "ASP.NET MVC - Creating a DropDownList helper for enums": http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

查看我的帖子,创建一个自定义助手“ASP”。NET MVC——为enums创建下拉列表帮助程序”:http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net- MVC -creating-a- droplist -helper-for aspx

#19


0  

If you would like to have a more user friendly description in your combo box (or other control) you can use the Description attribute with the following function:

如果您希望在组合框(或其他控件)中有更友好的用户描述,可以使用description属性,并具有以下功能:

    public static object GetEnumDescriptions(Type enumType)
    {
        var list = new List<KeyValuePair<Enum, string>>();
        foreach (Enum value in Enum.GetValues(enumType))
        {
            string description = value.ToString();
            FieldInfo fieldInfo = value.GetType().GetField(description);
            var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).First();
            if (attribute != null)
            {
                description = (attribute as DescriptionAttribute).Description;
            }
            list.Add(new KeyValuePair<Enum, string>(value, description));
        }
        return list;
    }

Here is an example of an enum with Description attributes applied:

下面是一个使用描述属性的枚举示例:

    enum SampleEnum
    {
        NormalNoSpaces,
        [Description("Description With Spaces")]
        DescriptionWithSpaces,
        [Description("50%")]
        Percent_50,
    }

Then Bind to control like so...

然后像这样绑定控制……

        m_Combo_Sample.DataSource = GetEnumDescriptions(typeof(SampleEnum));
        m_Combo_Sample.DisplayMember = "Value";
        m_Combo_Sample.ValueMember = "Key";

This way you can put whatever text you want in the drop down without it having to look like a variable name

这样你就可以把你想要的任何文本放到下拉列表中,而不需要看起来像一个变量名。

#20


0  

You could also use Extension methods. For those not familar with extensions I suggest checking the VB and C# documentation.

你也可以使用扩展方法。对于那些不熟悉扩展我建议检查VB和c#的文档。


VB Extension:

VB扩展:

Namespace CustomExtensions
    Public Module ListItemCollectionExtension

        <Runtime.CompilerServices.Extension()> _
        Public Sub AddEnum(Of TEnum As Structure)(items As System.Web.UI.WebControls.ListItemCollection)
            Dim enumerationType As System.Type = GetType(TEnum)
            Dim enumUnderType As System.Type = System.Enum.GetUnderlyingType(enumType)

            If Not enumerationType.IsEnum Then Throw New ArgumentException("Enumeration type is expected.")

            Dim enumTypeNames() As String = System.Enum.GetNames(enumerationType)
            Dim enumTypeValues() As TEnum = System.Enum.GetValues(enumerationType)

            For i = 0 To enumTypeNames.Length - 1
                items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), TryCast(enumTypeValues(i), System.Enum).ToString("d")))
            Next
        End Sub
    End Module
End Namespace

To use the extension:

使用扩展:

Imports <projectName>.CustomExtensions.ListItemCollectionExtension

...

yourDropDownList.Items.AddEnum(Of EnumType)()

C# Extension:

c#扩展:

namespace CustomExtensions
{
    public static class ListItemCollectionExtension
    {
        public static void AddEnum<TEnum>(this System.Web.UI.WebControls.ListItemCollection items) where TEnum : struct
        {
            System.Type enumType = typeof(TEnum);
            System.Type enumUnderType = System.Enum.GetUnderlyingType(enumType);

            if (!enumType.IsEnum) throw new Exception("Enumeration type is expected.");

            string[] enumTypeNames = System.Enum.GetNames(enumType);
            TEnum[] enumTypeValues = (TEnum[])System.Enum.GetValues(enumType);

            for (int i = 0; i < enumTypeValues.Length; i++)
            {
                items.add(new System.Web.UI.WebControls.ListItem(enumTypeNames[i], (enumTypeValues[i] as System.Enum).ToString("d")));
            }
        }
    }
}

To use the extension:

使用扩展:

using CustomExtensions.ListItemCollectionExtension;

...

yourDropDownList.Items.AddEnum<EnumType>()

If you want to set the selected item at the same time replace

如果您想同时设置所选项,请进行替换

items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), saveResponseTypeValues(i).ToString("d")))

with

Dim newListItem As System.Web.UI.WebControls.ListItem
newListItem = New System.Web.UI.WebControls.ListItem(enumTypeNames(i), Convert.ChangeType(enumTypeValues(i), enumUnderType).ToString())
newListItem.Selected = If(EqualityComparer(Of TEnum).Default.Equals(selected, saveResponseTypeValues(i)), True, False)
items.Add(newListItem)

By converting to System.Enum rather then int size and output issues are avoided. For example 0xFFFF0000 would be 4294901760 as an uint but would be -65536 as an int.

通过转换系统。避免了枚举而不是int大小和输出问题。例如0xff0000作为uint将是4294901760,而作为int将是-65536。

TryCast and as System.Enum are slightly faster than Convert.ChangeType(enumTypeValues[i], enumUnderType).ToString() (12:13 in my speed tests).

TryCast和系统。Enum比Convert要快一些。ChangeType(enumTypeValues[i], enumUnderType). tostring()(在我的speed test中为12:13)。

#21


0  

Both asp.net and winforms tutorial with combobox and dropdownlist: How to use Enum with Combobox in C# WinForms and Asp.Net

net和winforms教程都有combobox和dropdownlist:如何在c# winforms和asp.net中使用combobox

hope helps

希望能帮助

#22


0  

ASP.NET has since been updated with some more functionality, and you can now use built-in enum to dropdown.

ASP。NET已经更新了一些功能,现在您可以使用内置的enum来下拉。

If you want to bind on the Enum itself, use this:

如果您想在枚举本身上绑定,请使用以下命令:

@Html.DropDownList("response", EnumHelper.GetSelectList(typeof(Response)))

If you're binding on an instance of Response, use this:

如果您正在绑定一个响应实例,请使用以下方法:

// Assuming Model.Response is an instance of Response
@Html.EnumDropDownListFor(m => m.Response)

#23


0  

The accepted solution doesn't work, but the code below will help others looking for the shortest solution.

公认的解决方案不起作用,但是下面的代码将帮助其他人寻找最短的解决方案。

 foreach (string value in Enum.GetNames(typeof(Response)))
                    ddlResponse.Items.Add(new ListItem()
                    {
                        Text = value,
                        Value = ((int)Enum.Parse(typeof(Response), value)).ToString()
                    });

#24


0  

This is probably an old question.. but this is how I did mine.

这可能是个老问题。但我就是这样做的。

Model:

模型:

public class YourEntity
{
   public int ID { get; set; }
   public string Name{ get; set; }
   public string Description { get; set; }
   public OptionType Types { get; set; }
}

public enum OptionType
{
    Unknown,
    Option1, 
    Option2,
    Option3
}

Then in the View: here's how to use populate the dropdown.

然后在视图中:下面是如何使用下拉菜单。

@Html.EnumDropDownListFor(model => model.Types, htmlAttributes: new { @class = "form-control" })

This should populate everything in your enum list. Hope this helps..

这将填充枚举列表中的所有内容。希望这可以帮助. .

#1


104  

I probably wouldn't bind the data as it's an enum, and it won't change after compile time (unless I'm having one of those stoopid moments).

我可能不会绑定数据,因为它是enum,而且在编译时之后它也不会更改(除非我有一个stoopid时刻)。

Better just to iterate through the enum:

最好是在enum中迭代:

Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next

Or the same in C#

c#也是一样

Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(item);
}

#2


68  

Use the following utility class Enumeration to get an IDictionary<int,string> (Enum value & name pair) from an Enumeration; you then bind the IDictionary to a bindable Control.

使用以下实用工具类枚举从枚举中获取IDictionary (Enum值& name对);然后将IDictionary绑定到可绑定控件。 ,字符串>

public static class Enumeration
{
    public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct
    {
        var enumerationType = typeof (TEnum);

        if (!enumerationType.IsEnum)
            throw new ArgumentException("Enumeration type is expected.");

        var dictionary = new Dictionary<int, string>();

        foreach (int value in Enum.GetValues(enumerationType))
        {
            var name = Enum.GetName(enumerationType, value);
            dictionary.Add(value, name);
        }

        return dictionary;
    }
}

Example: Using the utility class to bind enumeration data to a control

示例:使用实用程序类将枚举数据绑定到控件

ddlResponse.DataSource = Enumeration.GetAll<Response>();
ddlResponse.DataTextField = "Value";
ddlResponse.DataValueField = "Key";
ddlResponse.DataBind();

#3


36  

I use this for ASP.NET MVC:

我用这个来表示ASP。NET MVC:

Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast<enumtype>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

#4


35  

My version is just a compressed form of the above:

我的版本只是上面的压缩格式:

foreach (Response r in Enum.GetValues(typeof(Response)))
{
    ListItem item = new ListItem(Enum.GetName(typeof(Response), r), r.ToString());
    DropDownList1.Items.Add(item);
}

#5


21  

public enum Color
{
    RED,
    GREEN,
    BLUE
}

Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:

每个Enum类型都来自System.Enum。有两个静态方法可以帮助将数据绑定到下拉列表控件(并检索值)。这些是枚举。getname Enum.Parse。使用GetNames,您可以绑定到下拉列表控件,如下所示:

protected System.Web.UI.WebControls.DropDownList ddColor;

private void Page_Load(object sender, System.EventArgs e)
{
     if(!IsPostBack)
     {
        ddColor.DataSource = Enum.GetNames(typeof(Color));
        ddColor.DataBind();
     }
}

Now if you want the Enum value Back on Selection ....

现在,如果你想要枚举值重新选择....

  private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   Color selectedColor = (Color)Enum.Parse(ddColor.SelectedValue); 
  }

#6


9  

After reading all posts I came up with a comprehensive solution to support showing enum description in dropdown list as well as selecting proper value from Model in dropdown when displaying in Edit mode:

在阅读了所有的文章后,我提出了一个全面的解决方案,在下拉列表中显示enum description,并在编辑模式下显示时从下拉列表中选择适当的值:

enum:

枚举:

using System.ComponentModel;
public enum CompanyType
{
    [Description("")]
    Null = 1,

    [Description("Supplier")]
    Supplier = 2,

    [Description("Customer")]
    Customer = 3
}

enum extension class:

enum扩展类:

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;

public static class EnumExtension
{
    public static string ToDescription(this System.Enum value)
    {
        var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : value.ToString();
    }

    public static IEnumerable<SelectListItem> ToSelectList<T>(this System.Enum enumValue)
    {
        return
            System.Enum.GetValues(enumValue.GetType()).Cast<T>()
                  .Select(
                      x =>
                      new SelectListItem
                          {
                              Text = ((System.Enum)(object) x).ToDescription(),
                              Value = x.ToString(),
                              Selected = (enumValue.Equals(x))
                          });
    }
}

Model class:

模型类:

public class Company
{
    public string CompanyName { get; set; }
    public CompanyType Type { get; set; }
}

and View:

和观点:

@Html.DropDownListFor(m => m.Type,
@Model.Type.ToSelectList<CompanyType>())

and if you are using that dropdown without binding to Model, you can use this instead:

如果你使用下拉菜单而不与模型绑定,你可以使用这个:

@Html.DropDownList("type",                  
Enum.GetValues(typeof(CompanyType)).Cast<CompanyType>()
.Select(x => new SelectListItem {Text = x.ToDescription(), Value = x.ToString()}))

So by doing so you can expect your dropdown displays Description instead of enum values. Also when it comes to Edit, your model will be updated by dropdown selected value after posting page.

因此,通过这样做,您可以期望您的下拉显示描述而不是枚举值。另外,当需要编辑时,您的模型将在发布页面后通过下拉选择值进行更新。

#7


8  

As others have already said - don't databind to an enum, unless you need to bind to different enums depending on situation. There are several ways to do this, a couple of examples below.

正如其他人已经说过的那样——不要将数据库绑定到enum,除非您需要根据情况绑定到不同的enum。有几种方法可以做到这一点,下面有几个例子。

ObjectDataSource

ObjectDataSource来

A declarative way of doing it with ObjectDataSource. First, create a BusinessObject class that will return the List to bind the DropDownList to:

使用ObjectDataSource实现此操作的声明式方法。首先,创建一个BusinessObject类,该类返回列表,将下拉列表绑定到:

public class DropDownData
{
    enum Responses { Yes = 1, No = 2, Maybe = 3 }

    public String Text { get; set; }
    public int Value { get; set; }

    public List<DropDownData> GetList()
    {
        var items = new List<DropDownData>();
        foreach (int value in Enum.GetValues(typeof(Responses)))
        {
            items.Add(new DropDownData
                          {
                              Text = Enum.GetName(typeof (Responses), value),
                              Value = value
                          });
        }
        return items;
    }
}

Then add some HTML markup to the ASPX page to point to this BO class:

然后向ASPX页面添加一些HTML标记,指向这个BO类:

<asp:DropDownList ID="DropDownList1" runat="server" 
    DataSourceID="ObjectDataSource1" DataTextField="Text" DataValueField="Value">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    SelectMethod="GetList" TypeName="DropDownData"></asp:ObjectDataSource>

This option requires no code behind.

此选项不需要后面的代码。

Code Behind DataBind

DataBind背后的代码

To minimize the HTML in the ASPX page and do bind in Code Behind:

为了最小化ASPX页面中的HTML并在后面绑定代码:

enum Responses { Yes = 1, No = 2, Maybe = 3 }

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        foreach (int value in Enum.GetValues(typeof(Responses)))
        {
            DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(Responses), value), value.ToString()));
        }
    }
}

Anyway, the trick is to let the Enum type methods of GetValues, GetNames etc. to do work for you.

总之,诀窍是让GetValues、GetNames等枚举类型方法为您工作。

#8


6  

I am not sure how to do it in ASP.NET but check out this post... it might help?

我不知道在ASP中怎么做。但看看这篇文章……它可能帮助吗?

Enum.GetValues(typeof(Response));

#9


5  

Array itemValues = Enum.GetValues(typeof(TaskStatus));
Array itemNames = Enum.GetNames(typeof(TaskStatus));

for (int i = 0; i <= itemNames.Length; i++)
{
    ListItem item = new ListItem(itemNames.GetValue(i).ToString(),
    itemValues.GetValue(i).ToString());
    ddlStatus.Items.Add(item);
}

#10


4  

public enum Color
{
    RED,
    GREEN,
    BLUE
}

ddColor.DataSource = Enum.GetNames(typeof(Color));
ddColor.DataBind();

#11


4  

You could use linq:

您可以使用linq:

var responseTypes= Enum.GetNames(typeof(Response)).Select(x => new { text = x, value = (int)Enum.Parse(typeof(Response), x) });
    DropDownList.DataSource = responseTypes;
    DropDownList.DataTextField = "text";
    DropDownList.DataValueField = "value";
    DropDownList.DataBind();

#12


3  

Generic Code Using Answer six.

使用回答6的通用代码。

public static void BindControlToEnum(DataBoundControl ControlToBind, Type type)
{
    //ListControl

    if (type == null)
        throw new ArgumentNullException("type");
    else if (ControlToBind==null )
        throw new ArgumentNullException("ControlToBind");
    if (!type.IsEnum)
        throw new ArgumentException("Only enumeration type is expected.");

    Dictionary<int, string> pairs = new Dictionary<int, string>();

    foreach (int i in Enum.GetValues(type))
    {
        pairs.Add(i, Enum.GetName(type, i));
    }
    ControlToBind.DataSource = pairs;
    ListControl lstControl = ControlToBind as ListControl;
    if (lstControl != null)
    {
        lstControl.DataTextField = "Value";
        lstControl.DataValueField = "Key";
    }
    ControlToBind.DataBind();

}

#13


3  

After finding this answer I came up with what I think is a better (at least more elegant) way of doing this, thought I'd come back and share it here.

在找到这个答案后,我想出了一个更好的方法(至少更优雅),我想我会回来分享它。

Page_Load:

Page_Load:

DropDownList1.DataSource = Enum.GetValues(typeof(Response));
DropDownList1.DataBind();

LoadValues:

LoadValues:

Response rIn = Response.Maybe;
DropDownList1.Text = rIn.ToString();

SaveValues:

SaveValues:

Response rOut = (Response) Enum.Parse(typeof(Response), DropDownList1.Text);

#14


1  

That's not quite what you're looking for, but might help:

这不是你想要的,但可能会有所帮助:

http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx

#15


1  

Why not use like this to be able pass every listControle :

为什么不用这样可以通过每个列表:


public static void BindToEnum(Type enumType, ListControl lc)
        {
            // get the names from the enumeration
            string[] names = Enum.GetNames(enumType);
            // get the values from the enumeration
            Array values = Enum.GetValues(enumType);
            // turn it into a hash table
            Hashtable ht = new Hashtable();
            for (int i = 0; i < names.Length; i++)
                // note the cast to integer here is important
                // otherwise we'll just get the enum string back again
                ht.Add(names[i], (int)values.GetValue(i));
            // return the dictionary to be bound to
            lc.DataSource = ht;
            lc.DataTextField = "Key";
            lc.DataValueField = "Value";
            lc.DataBind();
        }
And use is just as simple as :

BindToEnum(typeof(NewsType), DropDownList1);
BindToEnum(typeof(NewsType), CheckBoxList1);
BindToEnum(typeof(NewsType), RadoBuuttonList1);

#16


0  

This is my solution for Order an Enum and DataBind(Text and Value)to Dropdown using LINQ

这是我的解决方案,可以使用LINQ命令下拉Enum和DataBind(文本和值)

var mylist = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList<MyEnum>().OrderBy(l => l.ToString());
foreach (MyEnum item in mylist)
    ddlDivisao.Items.Add(new ListItem(item.ToString(), ((int)item).ToString()));

#17


0  

For some reason the answer provided by Mark Glorie didn't work for me. As the GetValues return an Array object and I couldn't use indexer to gets its items value. I tried itemsValue.GetValue(i) and it worked but unfortunately, it didn't populate the enum value to the dropdownlist item's value. It just populated enum item name as the text and value of the dropdownlist.

由于某种原因,马克·格洛里提供的答案对我不起作用。当GetValues返回一个数组对象时,我不能使用indexer获取它的items值。我尝试了itemsValue.GetValue(I),但不幸的是,它没有将enum项的值填充到enum值中。它只是填充枚举项名称作为下拉列表的文本和值。

I modified Mark's code further and have posted it as the solution here How to bind an Enum with its value to the DropDownList in ASP.NET?

我进一步修改了Mark的代码,并将其作为解决方案发布在这里,如何将枚举值绑定到ASP.NET中的下拉列表?

Hope this helps.

希望这个有帮助。

Thanks

谢谢

#18


0  

Check out my post on creating a custom helper "ASP.NET MVC - Creating a DropDownList helper for enums": http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

查看我的帖子,创建一个自定义助手“ASP”。NET MVC——为enums创建下拉列表帮助程序”:http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net- MVC -creating-a- droplist -helper-for aspx

#19


0  

If you would like to have a more user friendly description in your combo box (or other control) you can use the Description attribute with the following function:

如果您希望在组合框(或其他控件)中有更友好的用户描述,可以使用description属性,并具有以下功能:

    public static object GetEnumDescriptions(Type enumType)
    {
        var list = new List<KeyValuePair<Enum, string>>();
        foreach (Enum value in Enum.GetValues(enumType))
        {
            string description = value.ToString();
            FieldInfo fieldInfo = value.GetType().GetField(description);
            var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).First();
            if (attribute != null)
            {
                description = (attribute as DescriptionAttribute).Description;
            }
            list.Add(new KeyValuePair<Enum, string>(value, description));
        }
        return list;
    }

Here is an example of an enum with Description attributes applied:

下面是一个使用描述属性的枚举示例:

    enum SampleEnum
    {
        NormalNoSpaces,
        [Description("Description With Spaces")]
        DescriptionWithSpaces,
        [Description("50%")]
        Percent_50,
    }

Then Bind to control like so...

然后像这样绑定控制……

        m_Combo_Sample.DataSource = GetEnumDescriptions(typeof(SampleEnum));
        m_Combo_Sample.DisplayMember = "Value";
        m_Combo_Sample.ValueMember = "Key";

This way you can put whatever text you want in the drop down without it having to look like a variable name

这样你就可以把你想要的任何文本放到下拉列表中,而不需要看起来像一个变量名。

#20


0  

You could also use Extension methods. For those not familar with extensions I suggest checking the VB and C# documentation.

你也可以使用扩展方法。对于那些不熟悉扩展我建议检查VB和c#的文档。


VB Extension:

VB扩展:

Namespace CustomExtensions
    Public Module ListItemCollectionExtension

        <Runtime.CompilerServices.Extension()> _
        Public Sub AddEnum(Of TEnum As Structure)(items As System.Web.UI.WebControls.ListItemCollection)
            Dim enumerationType As System.Type = GetType(TEnum)
            Dim enumUnderType As System.Type = System.Enum.GetUnderlyingType(enumType)

            If Not enumerationType.IsEnum Then Throw New ArgumentException("Enumeration type is expected.")

            Dim enumTypeNames() As String = System.Enum.GetNames(enumerationType)
            Dim enumTypeValues() As TEnum = System.Enum.GetValues(enumerationType)

            For i = 0 To enumTypeNames.Length - 1
                items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), TryCast(enumTypeValues(i), System.Enum).ToString("d")))
            Next
        End Sub
    End Module
End Namespace

To use the extension:

使用扩展:

Imports <projectName>.CustomExtensions.ListItemCollectionExtension

...

yourDropDownList.Items.AddEnum(Of EnumType)()

C# Extension:

c#扩展:

namespace CustomExtensions
{
    public static class ListItemCollectionExtension
    {
        public static void AddEnum<TEnum>(this System.Web.UI.WebControls.ListItemCollection items) where TEnum : struct
        {
            System.Type enumType = typeof(TEnum);
            System.Type enumUnderType = System.Enum.GetUnderlyingType(enumType);

            if (!enumType.IsEnum) throw new Exception("Enumeration type is expected.");

            string[] enumTypeNames = System.Enum.GetNames(enumType);
            TEnum[] enumTypeValues = (TEnum[])System.Enum.GetValues(enumType);

            for (int i = 0; i < enumTypeValues.Length; i++)
            {
                items.add(new System.Web.UI.WebControls.ListItem(enumTypeNames[i], (enumTypeValues[i] as System.Enum).ToString("d")));
            }
        }
    }
}

To use the extension:

使用扩展:

using CustomExtensions.ListItemCollectionExtension;

...

yourDropDownList.Items.AddEnum<EnumType>()

If you want to set the selected item at the same time replace

如果您想同时设置所选项,请进行替换

items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), saveResponseTypeValues(i).ToString("d")))

with

Dim newListItem As System.Web.UI.WebControls.ListItem
newListItem = New System.Web.UI.WebControls.ListItem(enumTypeNames(i), Convert.ChangeType(enumTypeValues(i), enumUnderType).ToString())
newListItem.Selected = If(EqualityComparer(Of TEnum).Default.Equals(selected, saveResponseTypeValues(i)), True, False)
items.Add(newListItem)

By converting to System.Enum rather then int size and output issues are avoided. For example 0xFFFF0000 would be 4294901760 as an uint but would be -65536 as an int.

通过转换系统。避免了枚举而不是int大小和输出问题。例如0xff0000作为uint将是4294901760,而作为int将是-65536。

TryCast and as System.Enum are slightly faster than Convert.ChangeType(enumTypeValues[i], enumUnderType).ToString() (12:13 in my speed tests).

TryCast和系统。Enum比Convert要快一些。ChangeType(enumTypeValues[i], enumUnderType). tostring()(在我的speed test中为12:13)。

#21


0  

Both asp.net and winforms tutorial with combobox and dropdownlist: How to use Enum with Combobox in C# WinForms and Asp.Net

net和winforms教程都有combobox和dropdownlist:如何在c# winforms和asp.net中使用combobox

hope helps

希望能帮助

#22


0  

ASP.NET has since been updated with some more functionality, and you can now use built-in enum to dropdown.

ASP。NET已经更新了一些功能,现在您可以使用内置的enum来下拉。

If you want to bind on the Enum itself, use this:

如果您想在枚举本身上绑定,请使用以下命令:

@Html.DropDownList("response", EnumHelper.GetSelectList(typeof(Response)))

If you're binding on an instance of Response, use this:

如果您正在绑定一个响应实例,请使用以下方法:

// Assuming Model.Response is an instance of Response
@Html.EnumDropDownListFor(m => m.Response)

#23


0  

The accepted solution doesn't work, but the code below will help others looking for the shortest solution.

公认的解决方案不起作用,但是下面的代码将帮助其他人寻找最短的解决方案。

 foreach (string value in Enum.GetNames(typeof(Response)))
                    ddlResponse.Items.Add(new ListItem()
                    {
                        Text = value,
                        Value = ((int)Enum.Parse(typeof(Response), value)).ToString()
                    });

#24


0  

This is probably an old question.. but this is how I did mine.

这可能是个老问题。但我就是这样做的。

Model:

模型:

public class YourEntity
{
   public int ID { get; set; }
   public string Name{ get; set; }
   public string Description { get; set; }
   public OptionType Types { get; set; }
}

public enum OptionType
{
    Unknown,
    Option1, 
    Option2,
    Option3
}

Then in the View: here's how to use populate the dropdown.

然后在视图中:下面是如何使用下拉菜单。

@Html.EnumDropDownListFor(model => model.Types, htmlAttributes: new { @class = "form-control" })

This should populate everything in your enum list. Hope this helps..

这将填充枚举列表中的所有内容。希望这可以帮助. .