Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Using human readable enum values in a ComboBox

, 7 Feb 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Re-coded using LINQ. Stores the actual enum values in the combobox.public static void SetEnumValues(ComboBox cb){ Type t = typeof(T); if (!t.IsEnum) throw new ArgumentException("Only Enum types can be set"); cb.DisplayMember = "Key"; cb.ValueMember =...

Re-coded using LINQ. Stores the actual enum values in the combobox.

public static void SetEnumValues<T>(ComboBox cb)
{
    Type t = typeof(T);
 
    if (!t.IsEnum)
        throw new ArgumentException("Only Enum types can be set");
 
    cb.DisplayMember = "Key";
    cb.ValueMember = "Value";
    cb.DataSource = Enum.GetValues(t).Cast<T>().Select(
        val =>
        {
            string desc = Enum.GetName(t, val);
 
            DescriptionAttribute attr =
                ((DescriptionAttribute[])
                    t.GetField(desc).
                    GetCustomAttributes(typeof(DescriptionAttribute), false)).
                FirstOrDefault();
 
            return new KeyValuePair<string, T>(
                attr != null && !string.IsNullOrEmpty(attr.Description) ? attr.Description : desc,
                val);
        }).ToList();
}

Call with:

SetEnumValues<MyEnum>(myComboBox);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jarvisa
Software Developer (Senior) Shaw Inspection Systems Ltd
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 4 Nice work, but I don't see nothing n... PinmemberOshtri Deka29-Feb-12 22:11 
GeneralRe: The original code casted the enum values to int. By using ge... Pinmemberjarvisa29-Feb-12 23:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 7 Feb 2012
Article Copyright 2012 by jarvisa
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid