【问题标题】:Getting Id of enum which I have bound to a dropdown list获取我绑定到下拉列表的枚举 ID
【发布时间】:2014-06-18 14:01:31
【问题描述】:

我有一组绑定到下拉列表的枚举。

((DropDownList)control).DataSource = DefaultSync;
((DropDownList)control).DataBind();

这里的 Defaultsync 是包含 2 个枚举的列表。

List<MyEnum> DefaultSync=(List<SyncRequestTypeEnum>)(Enum.GetValues(typeof(SyncRequestTypeEnum)).Cast<SyncRequestTypeEnum>().Except(new SyncRequestTypeEnum[] { SyncRequestTypeEnum.ProjectLevel })).ToList();

现在我想根据用户对下拉列表的选择来获取枚举的 id。 我使用了以下代码,但它给出了一个错误,因为列表不包含它的值。

public int EnumID
{
    get
    {
        return Convert.ToInt32(ddlselection.Selectedvalue);
    }
    set
    {
        ddlselection.SelectedValue = Convert.ToString(value);
    } 
}

有人可以帮忙吗?

错误是: 'ddlselection 有一个无效的 SelectedValue,因为它不存在于项目列表中。 参数名称:值

【问题讨论】:

  • 您遇到的错误是什么?

标签: c#


【解决方案1】:

为了使用SelectedValue 属性,您需要指定数据项的哪个属性是值属性,哪个是显示的文本。我建议将您的代码更改为以下内容:

var list = control as DropDownList;
list.DataSource = Enum.GetValues(typeof(SyncRequestTypeEnum))
    .Cast<SyncRequestTypeEnum>()
    .Except(/*..*/)
    .Select(x => new KeyValuePair<SyncRequestTypeEnum, string>(x, x.ToString())
    .ToList();
list.DataValueField = "Key";
list.DataTextField = "Value";
list.DataBind();

您的财产应该可以正常工作。

MSDN上的另一个例子和更详细的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多