A Comprehensive Utility to Play with Enum
I am often asked by developers in my team to write a code that can convert the enum
s to a collection structure which will be useable as a data source to any ASP.NET and/or HTML control and would be exposeable by Web Services. However, Enum
s can also be used as a data source to any server side container controls, the problem is to use them in HTML controls with JSON format.
We have some utilities that can convert the numerous data structures to JSON format and DataTable
is one of them. To utilize such structure in Restful Services, I decided to write a code that converts any Enum
Type to DataTable
. It is a small but comprehensive utility which makes the developer's life easy. Hope you like it.
Enum to DataTable Convertor Function
public DataTableEnumToDataTable(Type enumType)
{
DataTable table = newDataTable();
table.Columns.Add("Desc", typeof(string));
table.Columns.Add("Id", Enum.GetUnderlyingType(enumType));
foreach (string name in Enum.GetNames(enumType))
{
table.Rows.Add(name.Replace('_', ' '), Enum.Parse(enumType, name));
}
return table;
}
Method Calling
DataTable dT = EnumToDataTable(typeof(ENUM_CURRENCY));
Conclusion
I love to write such tiny utilities which enable my team to smoothly fulfill the task in a timely manner. I always enjoy writing such utilities because these make my work enjoyable to me.