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

About Brendan Tompkins

Brendan runs CodeBetter.Com. He was twice awarded MVP for Microsoft .NET, and is a founder and the CTO of Quick180.Com More about Brendan at https://www.linkedin.com/codebetter
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://www.rhinestonewear.org custom rhinestone t shirts

    Strongly-Type a DropDownList with Enumerated Types

  • Rob
  • Brendan Tompkins
  • IT-Spot

    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())

    );

    }

  • Martin

    Hi, genius lines of code.

    thank’s a lot

  • Grant

    I didn’t know the GetValues() method of the Enum type return an Array — this is very good to know!

  • Brendan Tompkins

    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

  • Chris Martin

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

    public enum TShirtSize : Int16

    {



    }

  • Darrell

    Why are you converting TShirtSize to Int16? Aren’t enums Int32’s by default?

  • Marc Fairorth

    Elegant! Did I mention I had exactly this problem come up earlier today? Thanks.

  • Dave Burke

    That’s coooool! Really! I’ll have to play with this. Thanks, Brendan.