Billz
Billz

Reputation: 1097

convert an object (list of strings) into data table

I am working in C# and .net core. I have an object which consist of multiple lists of strings and i want to convert this object into datatable.

I have tried this code, but it failed:

public static DataTable ObjectToData(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, typeof(string));
            dt.Rows[0][f.Name] = f.GetValue(o, null);
        }
        catch { }
    });
    return dt;
}

Upvotes: 0

Views: 1649

Answers (2)

Generic convertion:

public DataTable ListToDataTable<T>(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;
    }

Upvotes: 2

TiGreX
TiGreX

Reputation: 1816

your problem is that you add the DataRow at the start of it. what you have to do is instanciate it, and then assign the values and finally add it to the datatable. Also change the add information into the row for the next dr[f.Name] = f.GetValue(o, null);

here is the code:

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

    DataRow dr = dt.NewRow();


    o.GetType().GetProperties().ToList().ForEach(f =>
    {
        try
        {
            f.GetValue(o, null);
            dt.Columns.Add(f.Name, typeof(string));
            dr[f.Name] = f.GetValue(o, null);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    });

    dt.Rows.Add(dr);

    return dt;
}

you can find an example here https://dotnetfiddle.net/EeegHg

Upvotes: 2

Related Questions