shrekDeep
shrekDeep

Reputation: 2328

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

Upvotes: 3

Views: 3175

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460288

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();

Upvotes: 7

Christos
Christos

Reputation: 53958

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.

Upvotes: 0

Related Questions