How to Fill a Dropdown with Enum Values in C#
By Tan Lee Published on Mar 04, 2025 159
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization