Loading ...

how-to-bind-enum-with-dropdown-list | CodeAsp.Net

How to bind enum with dropdown list

 /5
0 (0votes)

Recently i had faced a situation where i wanted to bind the values and names in the enum to the dropdownlist .After some research i found the way to do it. I'm sharing it with you guys.You can declare the enum like this :

public enum Days
{
  monday=1,
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
sunday
}

Now to bind the values and names to the dropdownlist i used Hashtable.As you all know Hashtable works on key and value pair.
So i bind the values of enum with Key and names with value .

   
 protected void Page_Load(object sender, EventArgs e)
    {
        Hashtable ht = BindEnum(typeof(Days));
        ddlDays.DataSource = ht;
        ddlDays.DataTextField = "value";
        ddlDays.DataValueField = "key";
        ddlDays.DataBind();
      
    }

    public Hashtable BindEnum(Type enumeration)
    {
        string[] names = Enum.GetNames(enumeration);
        Array values = Enum.GetValues(enumeration);
        Hashtable ht = new Hashtable();
        for (int i = 0; i < names.Length; i++)
        {
            ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
        }
        return ht;
    }

 

Comments (no comments yet)

Top Posts