如何将Enum绑定到ASP.NET中的DropDownList控件?

时间:2008-09-15 07:03:32

标签: c# .net asp.net

假设我有以下简单的枚举:

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

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

27 个答案:

答案 0 :(得分:106)

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

最好只是遍历枚举:

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

或者在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);
}

答案 1 :(得分:69)

使用以下实用工具类Enumeration枚举获取IDictionary<int,string>(枚举值和名称对);然后将 IDictionary 绑定到可绑定的Control。

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

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

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

答案 2 :(得分:40)

我将此用于 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() }))

答案 3 :(得分:35)

我的版本只是以上的压缩形式:

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

答案 4 :(得分:22)

public enum Color
{
    RED,
    GREEN,
    BLUE
}

每个枚举类型都派生自System.Enum。有两种静态方法可以帮助将数据绑定到下拉列表控件(并检索值)。这些是Enum.GetNames和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();
     }
}

现在,如果您希望Enum值返回选择....

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

答案 5 :(得分:11)

阅读完所有帖子后,我想出了一个全面的解决方案,支持在下拉列表中显示枚举说明,并在编辑模式下显示时从下拉列表中选择适当的值:

枚举:

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

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

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

枚举扩展类:

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

模特课:

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

和查看:

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

如果您在没有绑定到Model的情况下使用该下拉列表,则可以使用此代码:

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

通过这样做,您可以预期您的下拉列表显示Description而不是枚举值。此外,在编辑时,您的模型将在发布页面后通过下拉选择值进行更新。

答案 6 :(得分:8)

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

<强>的ObjectDataSource

使用ObjectDataSource执行此操作的声明方式。首先,创建一个BusinessObject类,它将返回List以将DropDownList绑定到:

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

然后将一些HTML标记添加到ASPX页面以指向此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>

此选项不需要代码。

DataBind背后的代码

最小化ASPX页面中的HTML并在Code Behind中进行绑定:

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

无论如何,诀窍是让GetValues,GetNames等的Enum类型方法为你工作。

答案 7 :(得分:6)

我不确定如何在ASP.NET中执行此操作,但请查看this帖子...这可能有帮助吗?

Enum.GetValues(typeof(Response));

答案 8 :(得分:5)

您可以使用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();

答案 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 :(得分:3)

使用答案六的通用代码。

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

}

答案 12 :(得分:3)

在找到这个答案之后,我想出了一个更好(至少更优雅)的方式来做这件事,以为我会回来在这里分享。

的Page_Load:

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

LoadValues:

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

SaveValues:

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

答案 13 :(得分:1)

为什么不这样使用才能传递每个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();
        }
使用就像下面这样简单:

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

答案 14 :(得分:1)

这可能是一个老问题..但这就是我的做法。

型号:

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
}

然后在视图中:这里是如何使用填充下拉列表。

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

这应填充枚举列表中的所有内容。希望这会有所帮助..

答案 15 :(得分:1)

答案 16 :(得分:1)

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

如果要绑定Enum本身,请使用:

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

如果你绑定了一个Response实例,请使用:

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

答案 17 :(得分:0)

我意识到这篇文章较旧并且适用于 Asp.net,但我想提供一个我最近用于 c# Windows 窗体项目的解决方案。这个想法是建立一个字典,其中键是枚举元素的名称,值是枚举值。然后将字典绑定到组合框。查看一个将 ComboBox 和 Enum 类型作为参数的通用函数。

    private void BuildComboBoxFromEnum(ComboBox box, Type enumType) {
        var dict = new Dictionary<string, int>();
        foreach (var foo in Enum.GetValues(enumType)) {
            dict.Add(foo.ToString(), (int)foo);
        }
        box.DropDownStyle = ComboBoxStyle.DropDownList; // Forces comboBox to ReadOnly
        box.DataSource = new BindingSource(dict, null);
        box.DisplayMember = "Key";
        box.ValueMember = "Value";
        // Register a callback that prints the Name and Value of the 
        // selected enum. This should be removed after initial testing.
        box.SelectedIndexChanged += (o, e) => {
            Console.WriteLine("{0} {1}", box.Text, box.SelectedValue);
        };
    }

这个函数可以如下使用:

BuildComboBoxFromEnum(comboBox1,typeof(Response));

答案 18 :(得分:0)

对于那些我们希望可以与任何drop和enum一起使用的C#解决方案的人...

private void LoadConsciousnessDrop()
{
    string sel_val = this.drp_Consciousness.SelectedValue;
    this.drp_Consciousness.Items.Clear();
    string[] names = Enum.GetNames(typeof(Consciousness));
    
    for (int i = 0; i < names.Length; i++)
        this.drp_Consciousness.Items.Add(new ListItem(names[i], ((int)((Consciousness)Enum.Parse(typeof(Consciousness), names[i]))).ToString()));

    this.drp_Consciousness.SelectedValue = String.IsNullOrWhiteSpace(sel_val) ? null : sel_val;
}

答案 19 :(得分:0)

您可以缩短操作时间

public enum Test
    {
        Test1 = 1,
        Test2 = 2,
        Test3 = 3
    }
    class Program
    {
        static void Main(string[] args)
        {

            var items = Enum.GetValues(typeof(Test));

            foreach (var item in items)
            {
                //Gives you the names
                Console.WriteLine(item);
            }


            foreach(var item in (Test[])items)
            {
                // Gives you the numbers
                Console.WriteLine((int)item);
            }
        }
    }

答案 20 :(得分:0)

在 ASP.NET Core 中,您可以使用以下 Html 帮助程序(来自 Microsoft.AspNetCore.Mvc.Rendering):

<select asp-items="Html.GetEnumSelectList<GridReportingStatusFilters>()">
     <option value=""></option>
</select>

答案 21 :(得分:0)

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

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

答案 22 :(得分:0)

您也可以使用扩展方法。对于那些不熟悉扩展程序的人,我建议您查看VBC#文档。


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

使用扩展程序:

Imports <projectName>.CustomExtensions.ListItemCollectionExtension

...

yourDropDownList.Items.AddEnum(Of EnumType)()

C#Extension:

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

使用扩展程序:

using CustomExtensions.ListItemCollectionExtension;

...

yourDropDownList.Items.AddEnum<EnumType>()

如果要同时设置所选项目,请替换

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

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)

通过转换为System.Enum而不是int size和输出问题。例如,0xFFFF0000作为uint将为4294901760,但作为int将为-65536。

TryCast和System.Enum略快于Convert.ChangeType(enumTypeValues [i],enumUnderType).ToString()(在我的速度测试中为12:13)。

答案 23 :(得分:0)

如果您希望在组合框(或其他控件)中拥有更加用户友好的描述,可以使用具有以下功能的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;
    }

以下是应用了Description属性的枚举示例:

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

然后绑定控制......

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

通过这种方式,您可以在下拉列表中放置所需的任何文本,而不必看起来像变量名称

答案 24 :(得分:0)

查看我关于创建自定义帮助程序的帖子“ASP.NET MVC - 为枚举创建DropDownList帮助程序”:http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx

答案 25 :(得分:0)

使用combobox和dropdownlist的asp.net和winforms教程: How to use Enum with Combobox in C# WinForms and Asp.Net

希望帮助

答案 26 :(得分:0)

这是我使用LINQ订阅枚举和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()));