Saturday, July 17, 2010

Get Names from Enum into Dropdownn list

In Order to get the names from the dropdown list from enumeration

public enum ProjectStatuses
{
NotStarted, InProgress, Completed
};

ddlPaymentStatus.DataSource = Enum.GetNames(typeof(ProjectStatuses));
ddlPaymentStatus.DataTextField = "Key";
ddlPaymentStatus.DataValueField = "Value";
ddlPaymentStatus.DataBind();

ProjectStatuses=Name of the Enum
ddlPaymentStatus=Name of Dropdown list

Also we can make a generic function for binding
//function to bind the dropdown list with enumeration
public static Hashtable BindToEnum(Type enumType)
{
//get the names from the enumeration
string[] names = Enum.GetNames(enumType);
//get the values from the enumeration
Array values = Enum.GetValues(enumType);

//turn this into hashtable
Hashtable ht = new Hashtable();
for (int i = 0; i < names.Length; i++)
{
ht.Add(names[i], values.GetValue(i));


}
return ht;
}

No comments:

Post a Comment