Showing posts with label Enum. Show all posts
Showing posts with label Enum. Show all posts

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)

Friday, August 15, 2008

How to count enum elements in C#?

If you need to count the enum elements ...

this is how you do it:

int nYourNumber = Enum.GetValues(typeof(YourEnumName)).Length;

as always: if you have something neater ;) comment ... I'll update the post if needed ;)