Imagine you have an enum defined in your code like so:
enum ContractType
{
Permanent = 1,
Contract = 2,
Internship = 99
}
Suppose we have a DropDownList on an ASP.NET page from which we'd like the user to select the appropriate ContractType
.
<asp:DropDownList runat="server" DataTextField="Key" DataValueField="Value" id="MyDropDownList">
Obviously, we can't do something as simple as
MyDropDownList.DataSource = ContractType;
as ContractType is a type, not an object. Instead, we can create a simple helper function that uses the Enum.GetValues
and Enum.GetNames
methods in order to create a Hashtable object (consisting of keys - Permanent, Contract, etc, and values - 1, 2 etc).
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 it into a hash table
Hashtable ht = new Hashtable();
for (int i = 0; i < names.Length; i++)
// note the cast to integer here is important
// otherwise we'll just get the enum string back again
ht.Add(names[i], (int)values.GetValue(i));
// return the dictionary to be bound to
return ht;
}
You can then use this as follows:
MyDropDownList.DataSource = BindToEnum(typeof(ContractType));
and we get a drop down list bound to the appropriate names/values as defined by the enum (note that we specified DataTextField and DataValueField in the earlier DropDownList definition).
Comments