ComboBox with Enum Descriptions
By FoxLearn 1/21/2025 6:12:08 AM 99
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 andComboBox.ValueMember
to the enum value. - Optionally, bind an object’s enum property to
ComboBox.SelectedValue
(notSelectedItem
).
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:
- Check
ComboBox.SelectedValue
directly. - Or bind an object’s enum property to
ComboBox.SelectedValue
(NOTSelectedItem
), 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
.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#