3

I have a problem with enum description. I want that the dataGrid show me the enum description and not "ToString()" of the enum.

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

I want to view the direction column by the description of the enum. What do I doing? Sorry for my bad English.

1 Answers1

1
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;
        }
    }
}
Chuck Wilbur
  • 2,510
  • 3
  • 26
  • 35
  • And if I want after it change the value of the enum ? –  Jan 19 '12 at 19:51
  • No no no no, I want to get the value of the enum, no set. –  Jan 19 '12 at 20:19
  • To get the value of the enum from this object you have at least two options I can think of immediately: 1) Add a public `GetDir()` function that will allow access programmatically without causing it to appear as a field in the `DataGridView`. 2) Inherit `Simple` from an `ISimple` interface that only exposes `Name` and `DirDesc` and pass your list to the `DataGridView` as a `List` instead of a `List`, then cast to a `Simple` to access the `dir` property later. – Chuck Wilbur Jan 19 '12 at 23:01
  • ...I didn't worry about editing the values because your current implementation just puts them in text boxes and if the user doesn't type the enum value exactly it throws exceptions. With the verbose descriptions that will be even worse, so I trust you're planning to change the `DirDesc` column to a combo box column and populate it with the legal choices... – Chuck Wilbur Jan 19 '12 at 23:08