Quick Data Binding to an Enumeration

by Paul Smith 2. October 2008 12:05

I recently got tired of writing the same code (below) to bind enumeration values to a control in ASP.NET.

   1: foreach (int value in Enum.GetValues(typeof(EnumName)))
   2: {
   3:     string name = Enum.GetName(typeof(EnumName), value);
   4:     li = new ListItem();
   5:     li.Text = name;
   6:     li.Value = value.ToString();
   7:     ListControl.Items.Add(li);
   8: }

So I decided to write a quick helper class to deal with sort of operation. Returning it as a DataTable made the most sense since it we easy to modify the headings for two-way data binding. Anyway I've posted the code below

   1: public class EnumUtilities<T> where T : struct
   2:     {
   3:         static EnumUtilities()
   4:         {
   5:             if (!typeof(T).IsEnum)
   6:             {
   7:                 throw new ArgumentException("Parameter T must be of type Enum");
   8:             }
   9:         }
  10:  
  11:         /// <summary>
  12:         /// Returns the Enumeration as a DataTable
  13:         /// </summary>
  14:         /// <param name="valueHeader">The name of the columns that contains the enumeration value</param>
  15:         /// <param name="textHeader">The name of the columns that contains the enumeration text</param>
  16:         public static DataTable GetAsDataTable(string valueHeader, string textHeader)
  17:         {
  18:             DataTable dt = new DataTable();
  19:  
  20:             dt.Columns.Add(valueHeader, typeof(int));
  21:             dt.Columns.Add(textHeader, typeof(string));
  22:  
  23:             foreach (int val in Enum.GetValues(typeof(T))) 
  24:             {
  25:                 dt.Rows.Add(new object[] { val, GetName(val) });
  26:             }
  27:  
  28:             return dt;
  29:         }
  30:  
  31:         /// <summary>
  32:         /// Parses a string to it's enumeration equivalent
  33:         /// </summary>
  34:         /// <param name="memberName"></param>
  36:         public static T Parse(string memberName)
  37:         {
  38:             return (T)Enum.Parse(typeof(T), memberName);
  39:         }
  40:  
  41:         /// <summary>
  42:         /// Gets the text value of an enumeration value from it's integer value
  43:         /// </summary>
  44:         /// <param name="value"></param>
  45:         /// <returns></returns>
  46:         public static string GetName(int value)
  47:         {
  48:             return Enum.GetName(typeof(T), value);
  49:         }
  50:     }

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

ASP.NET | C#

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen