2012-01-11 60 views
3

我遇到枚舉說明問題。 我想讓dataGrid顯示枚舉描述,而不是枚舉的「ToString()」。DataGridView中的枚舉說明

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: 
    } 
} 

我想通過enum的描述來查看方向列。 我該怎麼做? 對不起,我的英語不好。

回答

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; 
     } 
    } 
} 
+0

如果我想要改變枚舉的值? – zardav 2012-01-19 19:51:06

+0

不不不,不想不,我想要得到枚舉值,沒有設置。 – zardav 2012-01-19 20:19:54

+0

爲了從這個對象中獲得枚舉的值,你至少有兩個選擇我可以立即想到:1)添加一個公共'GetDir()'函數,它將允許以編程方式訪問,而不會使其作爲字段出現在' DataGridView'。 2)繼承'Simple'接口,該接口只暴露'Name'和'DirDesc',並將列表作爲'List '而不是'List '傳遞給'DataGridView',然後轉換爲'簡單''稍後訪問'dir'屬性。 – 2012-01-19 23:01:53