Here’s a method to convert a generic List
to a DataTable. This can be used with ObjectDataSource so you get automatic sorting, etc.
02 | /// Convert a List{T} to a DataTable. |
04 | private DataTable ToDataTable(List items) |
06 | var tb = new DataTable( typeof (T).Name); |
08 | PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance); |
10 | foreach (PropertyInfo prop in props) |
12 | Type t = GetCoreType(prop.PropertyType); |
13 | tb.Columns.Add(prop.Name, t); |
16 | foreach (T item in items) |
18 | var values = new object [props.Length]; |
20 | for ( int i = 0; i < props.Length; i++) |
22 | values[i] = props[i].GetValue(item, null ); |
32 | /// Determine of specified type is nullable |
34 | public static bool IsNullable(Type t) |
36 | return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof (Nullable<>)); |
40 | /// Return underlying type if type is Nullable otherwise return the type |
42 | public static Type GetCoreType(Type t) |
44 | if (t != null && IsNullable(t)) |
52 | return Nullable.GetUnderlyingType(t); |
No comments:
Post a Comment