Click here to Skip to main content
12,453,672 members (94,283 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.2K views
1 bookmarked
Posted

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

You may also be interested in...

Pro
Pro

Comments and Discussions

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

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web02 | 2.8.160826.1 | Last Updated 7 Feb 2012
Article Copyright 2012 by jarvisa
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid