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)

1 comment:

Andrew said...

Thanks a lot! Although I modified it a bit because I needed another structure:

DataTable dt = new DataTable(t.Name);
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Description", typeof(string));

string[] names = Enum.GetNames(t);
Array values = Enum.GetValues(t);
int i = 0;
foreach (string name in names)
{
DataRow dr = dt.NewRow();
dr[0] = values.GetValue(i++);
dr[1] = name;
dt.Rows.Add(dr);
}