ComboBox with Enum Descriptions

By FoxLearn 1/21/2025 6:12:08 AM   99
By default, when you load enum values into a ComboBox, it will display the enum names.

If you want to display the enum descriptions (from the [Description] attribute) instead, while still being able to retrieve the selected enum value, you can follow these steps:

  • Generate a list of objects containing pairs of enum values and their descriptions.
  • Set the ComboBox.DataSource to this list.
  • Set the ComboBox.DisplayMember to the description and ComboBox.ValueMember to the enum value.
  • Optionally, bind an object’s enum property to ComboBox.SelectedValue (not SelectedItem).

Consider the following enum with descriptions:

using System.ComponentModel;

public enum AnimalType
{
    [Description("Domestic Cat")]
    Cat,
    [Description("Wild Tiger")]
    Tiger
}

To display the descriptions in the ComboBox, you would generate a list of objects containing both the enum values and their descriptions (retrieved via reflection).

// Get the enum type either by hardcoding or reflection
Type enumType = typeof(AnimalType);

var enumValuesAndDescriptions = new ArrayList();

foreach (var e in Enum.GetValues(enumType))
{
    enumValuesAndDescriptions.Add(new
    {
        EnumValue = e,
        EnumDescription = (e.GetType().GetMember(e.ToString()).FirstOrDefault()
        .GetCustomAttributes(typeof(DescriptionAttribute), inherit: false).FirstOrDefault()
        as DescriptionAttribute)?.Description ?? e.ToString() // Defaults to the enum name if no description is found
    });
}

cbAnimalTypes.DataSource = enumValuesAndDescriptions;

// Set the DisplayMember and ValueMember to the appropriate properties from the anonymous objects
cbAnimalTypes.DisplayMember = "EnumDescription";
cbAnimalTypes.ValueMember = "EnumValue";

This approach using ArrayList works no matter how you get the enum type (hardcoded, from a generic type parameter, or reflected property type), since it avoids needing to cast the Array returned by Enum.GetValues().

It's recommended to use descriptive property names like EnumDescription and EnumValue.

Result: The ComboBox will show the descriptions of the enum values (e.g., "Domestic Cat" and "Wild Tiger").

Retrieving the Enum Value

To get the enum value (e.g., AnimalType.Cat) that the user selected, you can:

  1. Check ComboBox.SelectedValue directly.
  2. Or bind an object’s enum property to ComboBox.SelectedValue (NOT SelectedItem), like this:
var petOwner = new PetOwner()
{
    Name = "Alice",
    PetType = AnimalType.Cat
};

cbAnimalTypes.DataBindings.Add(nameof(ComboBox.SelectedValue), petOwner, nameof(PetOwner.PetType));

Notice that in this case, you use SelectedValue and not SelectedItem.