Let\'s say I have the following simple enum:
enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
How can I bind this enum to a DropDow
Use the following utility class Enumeration
to get an IDictionary
(Enum value & name pair) from an Enumeration; you then bind the IDictionary to a bindable Control.
public static class Enumeration
{
public static IDictionary GetAll() where TEnum: struct
{
var enumerationType = typeof (TEnum);
if (!enumerationType.IsEnum)
throw new ArgumentException("Enumeration type is expected.");
var dictionary = new Dictionary();
foreach (int value in Enum.GetValues(enumerationType))
{
var name = Enum.GetName(enumerationType, value);
dictionary.Add(value, name);
}
return dictionary;
}
}
Example: Using the utility class to bind enumeration data to a control
ddlResponse.DataSource = Enumeration.GetAll();
ddlResponse.DataTextField = "Value";
ddlResponse.DataValueField = "Key";
ddlResponse.DataBind();