How to map dropDownlist to enum in C#?

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)?

Last updated:12/2/2014 6:33:46 AM

1 Answers

Anonymous User
Anonymous User

private void BindDayOfWeek()
{
    this.ddlDayOfWeek.DataSource = GetWeekDays();
    this.ddlDayOfWeek.DataTextField = DayOfWeek;
    this.ddlDayOfWeek.DataValueField = (int)DayOfWeek.ToString();
    this.ddlDayOfWeek.DataBind();
}

Change your bind code to the above. This way the selected item of the drop down list, as all items, will have a text value that will be shown to the user and a value for this value, which you will can get it server side. The property value of the item, will give you the number of the selected day.

Answer