Wednesday, June 19, 2013

Convert IList to DataTable

To convert Ilist to datatable you can use bellow this code:
    public static DataTable ToDataTable(this IList data)
    {
        var properties = TypeDescriptor.GetProperties(typeof(T));
        var tableData = new DataTable();

        foreach (PropertyDescriptor prop in properties)
        {
            tableData.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }

        foreach (var item in data)
        {
            var row = tableData.NewRow();

            foreach (PropertyDescriptor prop in properties)
            {
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            }

            tableData.Rows.Add(row);
        }

        return tableData;
    }
If you have any query, feel free to get in touch please.

No comments:

Post a Comment