枚举说明值到下拉列表

本文关键字:下拉列表 说明 枚举 | 更新日期: 2023-09-27 18:33:44

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

我有一个类似

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

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

提前感谢!

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

枚举说明值到下拉列表

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 年和两份不同的工作,这正是您所说的需求。

这是

你写它的方式:

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

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

获取枚举值说明