Sunday 1 January 2012

HOW TO BIND AN ENUM TO DROPDOWNLIST

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class EnumDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var dictionary = new Dictionary<int, string>();
            foreach (int value in Enum.GetValues(typeof(Days)))
            {
                dictionary.Add(value, Enum.GetName(typeof(Days), value));
            }
            DropDownList1.DataSource = dictionary;
            DropDownList1.DataTextField = "value";
            DropDownList1.DataValueField = "key";
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0, "Select");
        }
    }
    protected enum Days
    {
        January=1,
        Frebuary,
        March,
        April,
        May,
        June,
        July,
        August,
        September,
        October,
        November,
        December
    };

No comments:

Post a Comment