C# 如何在 ASP.NET 中将 Enum 绑定到 DropDownList 控件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/61953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:20:47  来源:igfitidea点击:

How do you bind an Enum to a DropDownList control in ASP.NET?

提问by Ray

Let's say I have the following simple 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)?

采纳答案by Mark Glorie

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

我可能不会绑定数据,因为它是一个枚举,并且在编译后它不会改变(除非我遇到了那些愚蠢的时刻)。

Better just to iterate through the 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);
}

回答by roman m

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

回答by rudigrobler

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

我不知道如何在 ASP.NET 中做到这一点,但请查看这篇文章......它可能有帮助吗?

Enum.GetValues(typeof(Response));

回答by Leyu

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

使用以下实用程序类从EnumerationEnumeration获取IDictionary<int,string>(Enum 值和名称对);然后将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();

回答by Johan Danforth

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.

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

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 类,该类将返回 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;
    }
}

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

数据绑定背后的代码

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 等的 Enum 类型方法为您工作。

回答by VanOrman

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

回答by VanOrman

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。有两种静态方法可帮助将数据绑定到下拉列表控件(并检索值)。它们是 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();
     }
}

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

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

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

回答by VanOrman

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

回答by Mostafa

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

为什么不这样使用能够通过每个 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);

回答by Muhammed Qasim

Generic Code Using Answer six.

使用答案六的通用代码。

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

}