How to Fill a Dropdown with Enum Values in C#
By FoxLearn 3/4/2025 9:33:09 AM 80
To fill the dropdown with values from the CarBrand
enum, set the DataSource
property to Enum.GetValues()
, like this:
dropDownListCars.DataSource = Enum.GetValues(typeof(CarBrand));
If you need to show the enum’s Description
attribute instead of its name, check out how to display user-friendly descriptions.
To get the selected value from the dropdown, use:
var selectedCar = (CarBrand)dropDownListCars.SelectedItem;
When the form loads, the dropdown is automatically populated with car brands from the CarBrand
enum.
Binding to an Enum Property
If your controls are bound to an object, and one of the object’s properties is an enum, you can bind it to a dropdown like this:
person = new Person() { Name = "Alice", FavoriteCar = CarBrand.Toyota }; // Auto-populate the dropdown with enum values dropDownListCars.DataSource = Enum.GetValues(typeof(CarBrand)); // Bind the enum property dropDownListCars.DataBindings.Add(nameof(ComboBox.SelectedItem), person, nameof(person.FavoriteCar));
This approach ensures that your dropdown automatically displays all possible values and correctly binds to the FavoriteCar
property in the Person
object.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#