Consider this is because the object collection is returned, it is necessary to bind the object collection to DataGridView, binding DataGridView need the data source, assemble the data, it is troublesome to add columns with a DataTable, so it is possible to use reflection to achieve, it is estimated that there may be more than one place, May be used by different objects, so it is defined as generic
public class Datatablelisthelper<t> {public static DataTable Getdatatablehelper (list<t> items) {DataTable dt = new DataTable (); Type t = items[0]. GetType (); propertyinfo[] PiS = t.getproperties (); foreach (PropertyInfo pi in PiS) {dt. Columns.Add (pi. Name); } foreach (T item in items) {DataRow dr = dt. NewRow (); foreach (PropertyInfo pi in PiS) {Object obj = Pi. GetValue (item, NULL); Switch (pi. PropertyType.Name.ToString (). ToLower ()) {case "datetime": Dr[pi. Name] = convert.todatetime (obj). ToString ("Yyyy-mm-dd"); Break Case "Int32": Dr[pi. Name] = Convert.ToInt32 (obj); Break Case "Double": Dr[pi. Name] = convert.todouble (obj); Break Default:dr[pi. Name] = obj; Break }} dt. Rows.Add (DR); } return DT; } }
Switch type is not very full, you need to add some types
Conversely, if you convert a DataTable to an object, you can do it with reflection.
C # Reflection Application