The author of
this post has determined that this content is obsolete. Use at your own
risk! Blog posts are a point-in-time snapshot of the blogger’s thinking
and should not be assumed to represent this blogger’s current opinions.
This post was left up for historical purposes.
If you’re like me, you abhor any non-strongly typed sections of code like nature does a vacuum. Sometimes, it may seem unavoidable, like when creating a DropDownList (or other list type in the System.Web.UI.WebControls namespace, such as CheckBoxList). Here we usually resort to HTML definitions or other hard-coded representation of the ListItems that are to be presented. Your code might look like this:
<asp:DropDownList id=”sizeList” runat=”server”>
<asp:ListItem Value=”0″>Small</asp:ListItem>
<asp:ListItem Value=”1″>Medium</asp:ListItem>
<asp:ListItem Value=”2″>Large</asp:ListItem>
<asp:ListItem Value=”3″>ExtraLarge</asp:ListItem>
</asp:DropDownList>
There’s a problem with this approach, however. If the possible values in the list ever change, you’ll be faced with changing your presentation code, and any code that depends on any specific constants representing the possible values. You can get around these problems by strongly-typing the possible values for an enum, and using this to both generate the list and work with the user’s list selection.
First, create a strongly-typed enum containing your possible values, we’ll use t-shirt sizes for an example:
public
enum TShirtSize{
Small = 0,
Medium = 1,
Large = 2,
ExtraLarge = 3
}
Now, to dynamically create a drop-down list, use the following code:
DropDownList ddl = new DropDownList();
foreach(TShirtSize siz in Enum.GetValues(typeof(TShirtSize)))
{
ddl.Items.Add(
new ListItem(siz.ToString(), Convert.ToInt32(siz).ToString())
);
}
Now, to get back your strongly-typed value, use the following after a postback to find out the user’s selection.
TShirtSize selectedSize = (TShirtSize) Convert.ToInt32(ddl.SelectedValue);
Easy, and strongly typed!
-Brendan