C# 下拉列表的枚举描述值
我是C#的新手,我有个问题 我有一个类似的枚举C# 下拉列表的枚举描述值,c#,enums,C#,Enums,我是C#的新手,我有个问题 我有一个类似的枚举 public enum { [Description("1,2,3")] 123, [Description("3,4,5")] 345, [Description("6,7,8 ")] 678, } 现在,我希望枚举描述绑定到dropdownlist。。有人能帮我吗 提前谢谢 PS:如果我不清楚,我很抱歉。如果我需要更具体一些,请告诉我。您可以构建一个包装类,在
public enum
{
[Description("1,2,3")]
123,
[Description("3,4,5")]
345,
[Description("6,7,8 ")]
678,
}
现在,我希望枚举描述绑定到dropdownlist。。有人能帮我吗
提前谢谢
PS:如果我不清楚,我很抱歉。如果我需要更具体一些,请告诉我。您可以构建一个包装类,在每个成员上查找DescriptionAttribute并显示它。然后绑定到包装器实例。大概是这样的:
公共静态类EnumExtensionMethods
{
公共静态字符串GetDescription(此枚举枚举值)
{
对象[]attr=enumValue.GetType().GetField(enumValue.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute),false);
返回属性长度>0
((DescriptionAttribute)属性[0])。说明
:enumValue.ToString();
}
公共静态T ParseEnum(此字符串为stringVal)
{
返回(T)Enum.Parse(typeof(T),stringVal);
}
}
//与ASP.NET DropDownList一起使用
foreach(Enum.GetValues()中的MyEnum值)
添加(新的ListItem(value.GetDescription(),value.ToString())
...
var selectedEnumValue=myDDL.SelectedItem.Value.ParseEnum()
//WinForms组合框的用法
foreach(Enum.GetValues()中的MyEnum值)
添加(新的KeyValuePair(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);
下拉列表应该包含哪些内容?三项还是九项?请查看库。我尝试了此操作,但看不到GetEnumNames()和.GetCustomAttributes()我是否缺少一个程序集??是
类型
类的成员这将只获取具有Description属性的枚举项,而不会获取不具有该属性的枚举项。如果代码包含该属性,那将非常好,因此所有项都将在dropdownlist中可用。
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);