How to map dropDownlist to enum in C#?
asp.net, c#
Solution
Since the `SelectedValue` is a string you need to parse it first to `int`. Then you just need to cast it to `DayOfWeek`:
if(ddlDayOfWeek.SelectedIndex >= 0)
{
int selectedDay = int.Parse(ddlDayOfWeek.SelectedValue);
DayOfWeek day = (DayOfWeek) selectedDay;
}
If you don't separate the `DataTextField` and `DataValueField`(what you should) you can parse the `string` "Sunday" which is displayed in the `DropDownList` to `DayOfWeek` via `Enum.Parse`:
DayOfWeek selectedDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), ddlDayOfWeek.SelectedValue);
Edit: Here's an approach how you can set the `DataTextField/DataValueField` from the enum:
var weekDays = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>()
.Select(dow => new { Value = (int)dow, Text = dow.ToString() })
.ToList();
ddlDayOfWeek.DataSource = weekDays;
ddlDayOfWeek.DataTextField = "Text";
ddlDayOfWeek.DataValueField = "Value";
ddlDayOfWeek.DataBind();
Problem
I have bound a drop down list to the enum of days of week like this: ``` private void BindDayOfWeek() { this.ddlDayOfWeek.DataSource = GetWeekDays(); this.ddlDayOfWeek.DataBind(); } private List<DayOfWeek> GetWeekDays() { return Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>().ToList(); } ``` Now I want to read the int value of the selected week day (from dropdown list) which was in enum DayOfWeek i.e. if I select "Sunday" from dropdown, I should be able to pick the int value of "Sunday" in the enum DaysOfWeek (NOT ddlDayOfWeek.selectedValue OR SelectedIndex) How can I do that without a switch and if (Which I think can be one way)?