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

后端 未结 25 2597
既然无缘
既然无缘 2020-11-29 15:41

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 DropDow

25条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 16:29

    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:

    public class DropDownData
    {
        enum Responses { Yes = 1, No = 2, Maybe = 3 }
    
        public String Text { get; set; }
        public int Value { get; set; }
    
        public List GetList()
        {
            var items = new List();
            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:

    
    
    
    

    This option requires no code behind.

    Code Behind DataBind

    To minimize the HTML in the ASPX page and do bind in 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()));
            }
        }
    }
    

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

提交回复
热议问题