HOW TO MAP DROPDOWNLIST TO ENUM IN C#?

Jeet Verma

Total Post:110

Points:776
Posted by  Jeet Verma
C#  Dropdown 
 1065  View(s)
Ratings:
Rate this:

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

  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: How to map dropDownlist to enum in C#?

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!