-1

I want to convert a List to a Datatable. I am using the following code :

public static DataTable ConvertToDataTable(object o)
    {
        DataTable dt = new DataTable("OutputData");

        DataRow dr = dt.NewRow();
        dt.Rows.Add(dr);

        o.GetType().GetProperties().ToList().ForEach(f =>
        {
            try
            {
                f.GetValue(o, null);
                dt.Columns.Add(f.Name, f.PropertyType);
                dt.Rows[0][f.Name] = f.GetValue(o, null);
            }
            catch { }
        });
        return dt;
    }

The following is the class object that I am trying to pass to the ConverToDataTable method :

   public class Class1
   {

    private List<int> _intList;


    public List<int> intList
    {
        get
        {
            return _intList;
        }
        set
        {
            _intList = value;
        }
    }
}

But when I am trying to convert the class1 object to DataTable I am getting the datatable columns as count and Capacity.. What am I doing wrong?

Red Devil
  • 45
  • 3
  • 7
  • Are you wanting to add new rows for each element of `intList`? If so, you can't just assign the property to a row. – crashmstr Mar 18 '16 at 14:31
  • GetType().GetProperties() is getting the properties of the Type, not of the instance of your object. – CathalMF Mar 18 '16 at 15:06

2 Answers2

1

If you want to convert an integer list to Datatable you do not need to use Reflection. This can be solution.

public DataTable ConvertToDataTable(List<int> o)
{
    DataTable dt = new DataTable("OutputData");
    dt.Columns.Add("Integers", Type.GetType("System.Int32"));  
    foreach (var item in o)
    {
        DataRow dr = dt.NewRow();
        dt.Rows.Add(dr);
        dt.Rows[dt.Rows.Count - 1][0] = item;
    }           
    return dt;
}

But if you want to convert an object list to a datatable, then you have to use reflection.

aaltintop
  • 188
  • 9
0

of course because you are adding the list value not the integer values inside the list see this

Community
  • 1
  • 1
feras salim
  • 46
  • 10