1

Possible Duplicate:
.NET - Convert Generic Collection to DataTable

hi, i want to convert list datatype to datatype. i wrote the function

static DataTable ListToDataTable<T>(IEnumerable<T> list)
        {
            var dt = new DataTable();

            foreach (var info in typeof(T).GetProperties())
            {
                dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }
            foreach (var t in list)
            {
                var row = dt.NewRow();
                foreach (var info in typeof(T).GetProperties())
                {
                    row[info.Name] = info.GetValue(t, null);
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

but this is throwing exception "DataSet does not support System.Nullable<>" how can we solve this or is there any other solution

Community
  • 1
  • 1
neha dhage
  • 11
  • 1
  • 2

1 Answers1

0

Give this a try...

// When building table
Type pt = info.PropertyType;
if(pt.IsGenericType && pt.GetGenericTypeDefinition()==typeof(Nullable<>))
    pt = Nullable.GetUnderlyingType(pt);
}
dt.Columns.Add(new DataColumn(info.Name, pt)); 

// When loading table
row[info.Name] = info.GetValue(t, null) ?? DBNull.Value; 
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227