Home > DeveloperSection > Forums > How to map dropDownlist to enum in C#?
Jeet Verma
Jeet Verma

Total Post:110

Points:776
Posted on    December-01-2014 10:01 PM

 ASP.Net C#  Dropdown 
Ratings:


 1 Reply(s)
 618  View(s)
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)?



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    December-02-2014 6:33 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick