Skip to main content

Posts

Showing posts with the label create a DataTable from a Class

How to create a DataTable from a class?

Using Reflection to create a DataTable from a Class? //How to create a DataTable from a Class? public static DataTable CreateDataTable < T > (IEnumerable < T > list) { Type type = typeof(T); var properties = type . GetProperties (); DataTable dataTable = new DataTable(); foreach (PropertyInfo propertyinfo in properties) { dataTable . Columns .Add(new DataColumn( propertyinfo . Name , Nullable . GetUnderlyingType ( propertyinfo . PropertyType ) ?? propertyinfo . PropertyType )); } foreach (T entity in list) { object[] values = new object[ properties . Length ]; for ( int i = 0 ; i < properties . Length ; i + + ) { values [i] = properties[i].GetValue(entity); } dataTable . Rows .Add( values ); } return dataTable; }