Tuesday, March 2, 2010

Enum to DataTable

I had a lot of ENUM-s and needed to make DataTable - s with the same structure for pretty much all of them.
I came up with this:




private static DataTable CreateDataTable < TheSQLtable > ()
{
Type t = typeof(TheSQLtable);
if (!t.IsEnum)
{
throw new InvalidOperationException("Type is not Enum");
}

DataTable dt = new DataTable();
dt.TableName = t.Name;
DataColumn dc;

string[] names = Enum.GetNames(t);
foreach (string name in names)
{
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = name;
dc.Unique = false;
dt.Columns.Add(dc);
}

return dt;
}





(with a little help from stackoverflow)