1

Hi I am writing an extension method that converts list to datatable.

public static DataTable ToDataTable<T>(this IList<T> list)
    {
        DataTable table = new DataTable();

        var properties = typeof(T).GetProperties();
        int columns = properties.Count();

        foreach (var property in properties)
        {
            //set the column count in this list
            table.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
        }

        foreach(var element in list)
        {                                
            table.Rows.Add(element);
        }

        return table;
    }

Here Some column values might be null. How can i correctly map each value to table.Rows

Currently its trying to convert a list element to a column...i get error

Unable to cast object of type 'PracticeContractsListDTO' to type 'System.IConvertible'.Couldn't store PracticeContractsListDTO in PracticeContractId Column. Expected type is Int64.

Can't see what I am doing wrong.

Samra
  • 1,815
  • 4
  • 35
  • 71

0 Answers0