开发者

how to convert list to datatable [duplicate]

This question already has answers here: Closed 12 years ago.

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 i开发者_运维问答nfo 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


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; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜