How to show enum description in ComboBox?

In many cases you may need to show special characters, white spaces in your ComboBox when it is binded to enum. (Please see here my ‘binding to enums‘ post) Basically enums cannot have white spaces neither special characters like ‘ö’ or ‘á’, etc (it is not ought to use special characters in C# code). It is much beautiful if ComboBox shows clear and readable items. Let’s have a german example:

public enum Tier
{
    derHund,
    derFisch,
    dieSchildkrote
}

This will result the following:

The code is simple for this kind of binding, as you learned before:

comboBox1.DataSource = Enum.GetValues(typeof(Tier));

Now. Isn’t it much professional, if it looks like this:

ComboBox values with white spaces and special characters

First of all, add some descriptions to our Tier enum:



public enum Tier
{
    [Description("der Hund")]
    derHund,
    [Description("der Fisch")]
    derFisch,
    [Description("die Schildkröte")]
    dieSchildkrote
}

You can achieve this task with 2 really simple code snippets. One of them can be used elsewhere in your code. We create these 2 new methods as extension methods in a new static class, called Helpers:

public static class Helpers
    {
        public static string GetEnumDescription(this Enum input)
        {
            FieldInfo fi = input.GetType().GetField(input.ToString());

            if (fi.GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attributes &&
                attributes.Any())
            {
                return attributes.First().Description;
            }

            return input.ToString();
        }

        public static IList ToList(this Type type)
        {
            ArrayList list = new ArrayList();
            Array enumValues = Enum.GetValues(type);
            foreach (Enum value in enumValues)
            {
                list.Add(new KeyValuePair<Enum, string>(value, value.GetEnumDescription()));
            }

            return list;
        }
    }

The first extension method can be used on any Enum and will return with the description attribute. This can be also useful in any of your class where you use enum as property and want to override for example the ToString() method.

The second method will return a list of KeyValuePair, where we can use either the key or the value in our code. The input parameter must be a Type, which can be ‘typeof(Tier)’ in our example. As far as this is also an extension method, we should use it like this on our comboBox1:

comboBox1.DataSource = typeof(Tier).ToList();

Of course we have to tell the ComboBox which data should be shown (key or value) and which data will be the selection value:

comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

That’s all. In your application now you can bind your comboboxes to any of your enums with description using the above 3 lines of setting the datasource, display- and valuemembers.