0

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;
}
4
  • Please amend your question to at least show what you have been working with. Commented Sep 28, 2019 at 21:24
  • Update. I am get System.Collections.Generic.List`1[System.String] this in row as data Commented Sep 28, 2019 at 21:29
  • Possible duplicate of stackoverflow.com/questions/4981390/… Commented Sep 28, 2019 at 21:31
  • 1
    remove the try catch is hiding the exception Commented Sep 28, 2019 at 21:32

2 Answers 2

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.