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

时间:2020-03-05 18:53:11  来源:igfitidea点击:

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

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

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

解决方案

回答

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

最好只是遍历枚举:

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

回答

这不是我们要找的东西,但可能会有所帮助:

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

回答

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

Enum.GetValues(typeof(Response));

回答

使用下面的实用程序类Enumeration从枚举中获取IDictionary <int,string>(枚举值和名称对);然后将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;
    }
}

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

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

回答

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

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并在"隐藏代码"中进行绑定,请执行以下操作:

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类型方法为我们工作。

回答

我的版本只是上述内容的压缩形式:

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

回答

public enum Color
{
    RED,
    GREEN,
    BLUE
}

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

现在,如果我们想要枚举值,请返回"选择时..."。

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

回答

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

回答

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

Answer

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

}

回答

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

Page_Load:

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

负载值:

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

保存值:

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

标题数量不匹配

代码数量不匹配