Before we delve into the derived DropDownList, consider the
code that it is meant to replace. Let's say that we have an enum that
describes Status, and has possible values of Active, Inactive, Pending, and
Declined. We'll say these are for Proposal, so we'll call the enum
ProposalStatus.
Listing 1: ProposalStatus enum
public enum ProposalStatus
{
Active =1,
Inactive = 2,
Pending = 3,
Declined = 4
}
Now if we want to render a DropDownList that uses this enum
as its data source, we would use code like the following:
Listing 2: Binding Names to DropDownList
if (!Page.IsPostBack)
{
ProposalStatusDropDownList.DataSource =
Enum.GetNames(typeof(ProposalStatus));
ProposalStatusDropDownList.DataBind();
}
This will render a DropDownList with display and value both
as the name of the enum – the value is not stored in the DropDownList. To get
at the value, you would use code like this:
Listing 3: Getting a Strongly Typed Enum Value from
the DropDownList
protected void Button1_Click(object sender, EventArgs e)
{
ProposalStatus myStatus = (ProposalStatus)Enum.Parse(
typeof(ProposalStatus), ProposalStatusDropDownList.SelectedValue);
Label1.Text = myStatus.ToString();
}
Of course, if you actually want to store the enum’s numeric
value as the value of the DropDownList, the most effective way to achieve that
is to load up a SortedList<int,string> with the values and their
corresponding names, and then DataBind to this collection. This is easily done
with a helper method like the one shown in Listing 4. Note that since we
cannot use where T:System.Enum the best we can do is constrain T to be a struct
and then do a type check in code to verify it inherits from Enum.
Listing 4: Convert Enum to
SortedList<string,int> Collection
public static SortedList<string, int> GetEnumDataSource<T>() where T:struct
{
Type myEnumType = typeof(T);
if (myEnumType.BaseType != typeof(Enum))
{
throw new ArgumentException("Type T must inherit from System.Enum.");
}
SortedList<string, int> returnCollection = new SortedList<string, int>();
string[] enumNames = Enum.GetNames(myEnumType);
for (int i = 0; i < enumNames.Length; i++)
{
returnCollection.Add(enumNames[i],
(int)Enum.Parse(myEnumType, enumNames[i]));
}
return returnCollection;
}
Then to use this method with a DropDownList we would use
code like what is shown in Listing 5.
Listing 5: Bind to SortedList from Enum
ProposalStatusDropDownList2.DataSource =
GetEnumDataSource<ProposalStatus>();
ProposalStatusDropDownList2.DataValueField = "Value";
ProposalStatusDropDownList2.DataTextField = "Key";
ProposalStatusDropDownList2.DataBind();