Suppose I have several enums representing … for example database vendors: Unknown, Oracle, Sybase, SQL Server 2005, SQL Server 2008, etc. I want to let the user select between all of these but an Unknown from a Combo Box. When the user selects an enum, they should see a human-readable description (which would hopefully come from an attribute). However, the actual object selected should be an enum of that specific type.
This can be hacked together manually with the help of extra dictionary, but I do not want to do that, and rather use an idiomatic and the cleanest way possible.
Would you kindly share a code sample, or at least a good link?
P.S. Is there an easy way to grab a collection of all enums of the type vendor, except for Unknown (which will have a short/int value of 0, as prescribed by Bill Wagner)?
To associate a friendly name to the values, you can use
DescriptionAttribute, as shown in this answer. Handle theFormatevent of theComboBoxto display the description:Note: if your application needs to be localizable, the
Descriptionattribute is probably not the best option. Instead, you could use string resources with names likeDisplayName_DbVendor_Oracle,DisplayName_DbVendor_SqlServer, etc. You can then retrieve the display name for a value as follows:EDIT: if you need to sort the values by description, just change the LINQ query as follows: