Jun 5, 2010

Enum bind into dropdownlist using HasTable

You can create a method to help you convert your enum into a hashtable and then bind it to the ddl:



protected void Page_Load(object sender, EventArgs e)
{
Hashtable ht = GetEnumForBind(typeof(Salutations));
DropDownList1.DataSource = ht;
DropDownList1.DataTextField = "value";
DropDownList1.DataValueField = "key";

DropDownList1.DataBind();

}

public Hashtable GetEnumForBind(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;
}

No comments:

Post a Comment