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

后端 未结 25 2589
既然无缘
既然无缘 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:14

    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:

    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(typeof(Color),ddColor.SelectedValue
      }
    

提交回复
热议问题