【问题标题】:enum description value to dropdownlist枚举描述值到下拉列表
【发布时间】:2012-05-17 07:53:18
【问题描述】:

我是 C# 新手,我有一个问题,

我有一个类似的枚举

   public enum
        {
    [Description("1,2,3")]
    123,
    [Description("3,4,5")]
    345,
    [Description("6,7,8 ")]
    678,
       }

现在我希望枚举描述绑定到下拉列表.. 有人可以帮助我吗..

提前致谢!

PS:如果我不清楚,我很抱歉。如果我需要更具体,请告诉我

【问题讨论】:

  • 下拉菜单应该包含什么?三件还是九件?
  • 看看Humanizer库。

标签: c# enums


【解决方案1】:
public static class EnumExtensionMethods
{
    public static string GetDescription(this Enum enumValue)
    {
        object[] attr = enumValue.GetType().GetField(enumValue.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false);

        return attr.Length > 0 
           ? ((DescriptionAttribute) attr[0]).Description 
           : enumValue.ToString();            
    }

    public static T ParseEnum<T>(this string stringVal)
    {
        return (T) Enum.Parse(typeof (T), stringVal);
    }
}

//Usage with an ASP.NET DropDownList
foreach(MyEnum value in Enum.GetValues<MyEnum>())
   myDDL.Items.Add(New ListItem(value.GetDescription(), value.ToString())
...
var selectedEnumValue = myDDL.SelectedItem.Value.ParseEnum<MyEnum>()

//Usage with a WinForms ComboBox
foreach(MyEnum value in Enum.GetValues<MyEnum>())
   myComboBox.Items.Add(new KeyValuePair<string, MyEnum>(value.GetDescription(), value));

myComboBox.DisplayMember = "Key";
myComboBox.ValueMember = "Value";
...
var selectedEnumValue = myComboBox.SelectedItem.Value;

这两种扩展方法对我来说是非常宝贵的,因为我已经做了 5 年和两种不同的工作,完全满足您的需求。

【讨论】:

    【解决方案2】:

    你会这样写:

    public enum Test
    {
      [Description("1,2,3")]
      a = 123,
      [Description("3,4,5")]
      b = 345,
      [Description("6,7,8")]
      c = 678
    }
    
    //Get attributes from the enum
        var items = 
           typeof(Test).GetEnumNames()
            .Select (x => typeof(Test).GetMember(x)[0].GetCustomAttributes(
               typeof(DescriptionAttribute), false))
            .SelectMany(x => 
               x.Select (y => new ListItem(((DescriptionAttribute)y).Description)))
    
    //Add items to ddl
        foreach(var item in items)
           ddl.Items.Add(item);
    

    【讨论】:

    • 我试过了,但我看不到 GetEnumNames() 和 .GetCustomAttributes() 我错过了一个程序集吗??
    • GetEnumNames()Type 类的成员
    • 这只会采用具有描述属性的枚举项目,不会采用没有该属性的枚举项目。如果代码能够做到这一点,那就太好了,所以所有项目都将在下拉列表中可用。
    【解决方案3】:

    您可以构建一个包装类,在每个成员上查找 DescriptionAttribute 并显示它。然后绑定到包装器实例。像这样的:

    Get the Enum<T> value Description

    【讨论】:

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