我的枚举说明有问题。 我希望dataGrid向我显示枚举描述,而不是enum的“ToString()”。
enum DirectionEnum
{
[Description("Right to left")]
rtl,
[Description("Left to right")]
ltr
}
class Simple
{
[DisplayName("Name")]
public string Name { get; set; }
[DisplayName("Direction")]
public DirectionEnum dir { get; set; }
}
class DirectionDialog : Form
{
public DirectionDialog()
{
DataGridView table = new DataGridView();
List<Simple> list = new List<Simple>(new Simple[]{
new Simple{ Name = "dave", dir = DirectionEnum.ltr},
new Simple{ Name = "dan", dir = DirectionEnum.rtl }
});
table.DataSource = list;
//view "rtl" or "ltr" in "Direction"
//I want "Right to left" or "Left to right:
}
}
我想通过枚举的描述来查看方向列。 我在做什么? 抱歉我的英语不好。
答案 0 :(得分:2)
class Simple
{
[DisplayName("Name")]
public string Name { get; set; }
// Remove external access to the enum value
public DirectionEnum dir { private get; set; }
// Add a new string property for the description
[DisplayName("Direction")]
public string DirDesc
{
get
{
System.Reflection.FieldInfo field = dir.GetType().GetField(dir.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? dir.ToString() : attribute.Description;
}
}
}