无法将枚举值转换为组合框值

时间:2015-05-28 18:23:20

标签: c# winforms

我有一个绑定到枚举的组合框(通过绑定源)。我按如下方式填充组合框:

var list = new List<KeyValuePair<MyEnum, string>>();
list.Add(new KeyValuePair<MyEnum, string>(myEnum.Customer, "Customer"));

cbo.DataSource = list;
cbo.DisplayMember = "Value";
cbo.ValueMember = "Key";

我也有这个活动:

private void cbo_SelectedValueChanged(object sender, EventArgs e)
{
    if (cbo.SelectedValue == null)
        return;

    var value = (KeyValuePair<MyEnum, string>)cbo.SelectedValue;
    var item = (MyEnum)value.Key;

    if (item == MyEnum.Customer)
    { //Do someting... }
 }

但是,我得到了例外:

  

指定的演员表无效

设置cbo.ValueMember

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果我没记错的话,在这种情况下,SelectedValue只会包含Enum值,因为您已指定该值存储在&#34; Key&#34;属性与行

var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();

 AuthenticationManager.SignIn(
                new AuthenticationProperties { IsPersistent = isPersistent }, 
                userIdentity);

如果您修改这样的代码,它应该可以工作:

cbo.ValueMember = "Key";

cbo.DisplayMember = "Value"; // Please note that it is important to set the DisplayMember 
cbo.ValueMember = "Key";     // and ValueMember before assigning the DataSource

var list = new List<KeyValuePair<MyEnum, string>>();
list.Add(new KeyValuePair<MyEnum, string>(myEnum.Customer, "Customer"));
cbo.DataSource = list;