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 DropDownList with .NET Attributes!

A while back I posted about using an enum as a datasource for your drop-down lists, see Strongly-Type a DropDownList with Enumerated Types.  As it turns out, the big drawback to this approach is that your DropDownList's text is limited to the text that you use in your enum.  This is fine if your text doesn't have any spaces, or other special characters, since enumerations don't allow these.  But most of the time, you'll need a more presentable version of your text to show to your end-users. 

One approach would be to create a method to convert your enumerated value to text, switching on the value.  This isn't the best approach, however, because you've now logically separated the original enum from it's text representation, which can lead to some problems with maintenance.  Also the code for doing this can get ugly, and really should probably be relegated to The Daily WTF

Fortunately, there's a better way: Attributes.  I've been reading Applied .NET Attributes, by Jason Bock and Tom Barnaby recently, and attributes are a perfect solution to this problem.  They keep the meaning of the enum together with the definition, and the code to access this information is simple and straight forward.   So, here's the code from the last post, re-written to use attributes:

The new enumeration, with the Description attribute:

public enum TShirtSize
{
      [Description("Small (size 0-5)")] Small =
0,
      [Description("Medium (size 6-10)")] Medium =
1,
      [Description("Large (size 10-13)")] Large =
2,
      [Description("Extra-Large (sizes 13 and up)")] ExtraLarge =
3
}

A helper method to reflect and get the Description:

public static string GetDescription(Enum value)
{
  FieldInfo fi= value.GetType().GetField(value.ToString());
  DescriptionAttribute[] attributes =

     (DescriptionAttribute[])fi.
GetCustomAttributes(typeof(DescriptionAttribute), false);
  return (attributes.
Length>0) ? attributes[0].Description : value.ToString();
}

And finally, our new ddl code:

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

For more on this, see this great article, Mapping Text to Enum entries By Reto Ravasio

-Brendan



Comments

Brenton House said:

We found building translator classes to convert from enum to string was necessary as we defining our enum on the service side of a web service and using it on the client side. It loses the attributes when going through the web service. If anyone has a better suggestion, please let me know!
# December 8, 2004 5:13 AM

Brendan Tompkins said:

Hmmm. Yes, I can see this being a problem. At the least, your translator class could just be a wrapper to the GetDescrition() method on the server, right?
# December 8, 2004 5:18 AM

Dave Donaldson said:

Nice. Thanks.
# December 8, 2004 11:11 AM

Mihir Solanki said:

cool !!!
# December 8, 2004 8:48 PM

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