posted 3/10/2009 by Sumit Arora
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; }
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18