user14004290
user14004290

Reputation:

How to convert Collections to Datatable

Can you please help me to solve this problem
And is that I want to affect object de type collection Adhérent to datatable

Code:

BiblioEntities b = new BiblioEntities();
var ad = b.Adhérent.SqlQuery(@"select * from Adhérent ").ToList();
DataTable dt = (DataTable)ad;

Error:

Impossible de convertir le type 'System.Collections.Generic.List<Biblio.Adhérent>' en 'System.Data.DataTable'

Upvotes: 0

Views: 694

Answers (2)

SteveC
SteveC

Reputation: 6015

Here's another implementation

    public static class DataTableConverter
    {
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }
    }

To add to your code:

var dt = DataTableConverter.ToDataTable(ad);

Upvotes: 0

iSR5
iSR5

Reputation: 3498

I used the following extension with Entity Framework models, it would work with any type of collection :

public static System.Data.DataTable ToDataTable<T>(this IEnumerable<T> source)
{
    var table = new System.Data.DataTable(typeof(T).Name);

    var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (var prop in props)
    {
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }

    foreach (var item in source)
    {
        var values = new object[props.Length];
        for (var i = 0; i < props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        table.Rows.Add(values);
    }

    return table;
}

and applying it to your sample code would be like this :

var dt= new BiblioEntities().Adhérent.SqlQuery(@"select * from Adhérent ").ToDataTable();

Upvotes: 1

Related Questions