Convert Enum to Collection For DataBinding

I had a need to convert an enum to a collection for binding and I came across the solution from here

In addition, I thought I'd post an method I've coded before where I needed enum values for binding to (ID and Name) but since enum names cannot contain spaces and I needed the DataTextField (binding with dropdownlist then) to be user friendly. What I did was use DescriptionAttribute for the enum entries and use Reflection to determine the string/text for the enum values.

There is probably a more efficient way to do this but posting nevertheless. Also, I'm honestly not sure where I got the idea for this or if I had a reference so I wouldn't easily claim the code.

[more]

 ** Note that "Entity" below is just a class with public properties  ID(int) and Name(string) and contains an overloaded constructor which accepts parameters ID and Name

   66 public static Collection<Entity> GetBindableEnum(

   67             Enum en)

   68         {

   69             Collection<Entity> retVal = new Collection<Entity>();

   70             Type enumType = en.GetType();

   71             FieldInfo[] fields =

   72                 enumType.GetFields(

   73                     BindingFlags.Public |

   74                     BindingFlags.Static);

   75 

   76             foreach (FieldInfo fld in fields)

   77             {

   78                 // See if the member has a Description attribute:

   79                 object[] descriptionAttributes =

   80                     fld.GetCustomAttributes(

   81                         typeof (DescriptionAttribute), true);

   82 

   83                 if (descriptionAttributes.Length > 0)

   84                 {

   85                     string description = ((DescriptionAttribute) descriptionAttributes[0]).Description;

   86                     int value = Convert.ToInt32(fld.GetValue(en));

   87                     retVal.Add(

   88                         new Entity(

   89                             value,

   90                             description));

   91                 }

   92             }

   93 

   94             return retVal;

   95         }

 Here's an example of an enum with description:

   97 public enum RecurrencePattern

   98         {

   99             [Description("Run Once")]

  100             RunOnce = 1,

  101             [Description("Daily")]

  102             Daily,

  103             [Description("Weekly")]

  104             Weekly,

  105             [Description("Monthly")]

  106             Monthly

  107         }

calling GetBindableEnum(new RecurrencePattern()) should return the Collection of Entity(ies)

Ohh and I just read one of his other blog entries and looks like this is a good addition : Enums and Custom Attributes 

 


Posted

in

by

Tags: