How to fill a datatable with List<T>

MikaAK picture MikaAK · Sep 29, 2013 · Viewed 154.6k times · Source

How can convert a list to a datatable

[Serializable]
public class Item
{
    public string Name { get; set; }
    public double Price { get; set; }
    public string @URL { get; set; }

    public Item(string Name, string Price, string @URL)
    {
        this.Name = Name;
        this.Price = Convert.ToDouble(Price);
        this.@URL = @URL;
    }

    public override string ToString()
    {
        return this.Name;
    }
}

I tried using:

static DataTable ConvertToDatatable(List<Item> list)
{
    DataTable dt = new DataTable();

    dt.Columns.Add("Name");
    dt.Columns.Add("Price");
    dt.Columns.Add("URL");
    foreach (var item in list)
    {
        dt.Rows.Add(item.Name, Convert.ToString(item.Price), item.URL);
    }

    return dt;
}

Now I'm getting a box show up but its empty! Help!! What can i do to make the box actually have data?

Answer

immy picture immy · Jan 10, 2014

Just in case you have a nullable property in your class object:

private static DataTable ConvertToDatatable<T>(List<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
        else
            table.Columns.Add(prop.Name, prop.PropertyType);
    }

    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
 }