本文介绍了如何将dropDownlist映射到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();
    }

现在,我想从枚举DayOfWeek中读取所选星期几(从下拉列表中)的int值,即,如果我从下拉列表中选择"Sunday",我应该能够在其中选择"Sunday"的int值.枚举DaysOfWeek(不是ddlDayOfWeek.selectedValue或SelectedIndex)

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

推荐答案

由于 SelectedValue 是一个字符串,您需要首先将其解析为 int .然后,您只需要将其转换为 DayOfWeek :

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;
}

如果您不分隔 DataTextField DataValueField (应该怎么做),则可以解析显示的 string "Sunday"通过 Enum.Parse DropDownList DayOfWeek 中:

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

编辑:这是一种从枚举中设置 DataTextField/DataValueField 的方法:

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

这篇关于如何将dropDownlist映射到C#中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:30