CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Brendan Tompkins [MVP]

Blog First. Ask Questions Later.

Strongly-Type a DropDownList with Enumerated Types

OBSOLETE CONTENT
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



Comments

Marc Fairorth said:

Elegant! Did I mention I had exactly this problem come up earlier today? Thanks.
# April 6, 2004 4:21 PM

Darrell said:

Why are you converting TShirtSize to Int16? Aren't enums Int32's by default?
# April 6, 2004 4:50 PM

Chris Martin said:

You should declare your enum like so if you need Int16 for some reason:

public enum TShirtSize : Int16
{
...
}
# April 6, 2004 8:05 PM

Brendan Tompkins said:

Darrell, Chris good points. I guess it's faster converting to the bigger int. I guess I was thinking that the possible values would be small, so don't need an Int32... Anyhow. I've fixed the code.

-B
# April 7, 2004 1:39 AM

Grant said:

I didn't know the GetValues() method of the Enum type return an Array -- this is very good to know!
# April 7, 2004 3:53 AM

Martin said:

Hi, genius lines of code.

thank's a lot
# December 2, 2004 12:08 AM

IT-Spot said:

Better still to make a custom Convert method for your enum first to avoid unboxing.

public string ConvertToString(TShirtSize t)
{
string res;
switch(t)
{
case Small:
res = "Small";
break;
.......
}
return res;
}

/**
The same for int
/**

DropDownList ddl = new DropDownList();
foreach(TShirtSize siz in Enum.GetValues(typeof(TShirtSize)))
{
ddl.Items.Add(
new ListItem(ConvertToString(siz), ConvertToInt(siz).ToString())
);
}



# January 20, 2005 12:05 AM

Brendan Tompkins said:

# January 20, 2005 1:12 AM

Rob said:

# March 3, 2005 5:05 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Brendan Tompkins

Brendan has been programming with .NET since the first public beta and is owner and operator of Port Technology Services, a consultancy company providing .NET application development services to the Maritime industry. In July, 2007, he was awarded the Microsoft MVP award for ASP.NET. He's also a proud co-founder of failed .COM startup Intrinsigo, and has had a hand in the failure of numerous other businesses. He currently runs CodeBetter.Com and Devlicio.us, and lives in Norfolk, Virgina with his wife Tiara and son Ian.

View Brendan's profile on LinkedIn

Check out Devlicio.us!

Our Sponsors