Thursday, May 15, 2008

Convert ArrayList of Objects to DataTable

using System;using System.Collections;
using System.Data;using System.Reflection;
using System.Collections.Generic;
using System.Text;

public static class Util
{
public static DataTable ConvertArrayListToDataTable(ArrayList arrayList)
{
DataTable dt = new DataTable();

if (arrayList.Count != 0)
{
dt = ConvertObjectToDataTableSchema(arrayList[0]);
FillData(arrayList, dt);
}

return dt;
}

public static DataTable ConvertObjectToDataTableSchema(Object o)
{
DataTable dt = new DataTable();
PropertyInfo[] properties = o.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{
DataColumn dc = new DataColumn(property.Name);
dc.DataType = property.PropertyType; dt.Columns.Add(dc);
}
return dt;
}

private static void FillData(ArrayList arrayList, DataTable dt)
{
foreach (Object o in arrayList)
{
DataRow dr = dt.NewRow();
PropertyInfo[] properties = o.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{
dr[property.Name] = property.GetValue(o, null);
}
dt.Rows.Add(dr);
}
}
}

7 comments:

Anonymous said...

Thanks a lot. Precisely what i was looking for. Instead of myself creating the code myself I could just 'borrow' your solution.

Since 1987 said...

your code doesnt work for me!
error in converting

Tan Kok Beng said...

Thanks for the code snippet. Very useful indeed.

mgthantzin said...

Thank you for this code.

kate said...

Thanks for share you code.It helps a lot.

Anonymous said...

thank a lot

Khải Trần said...

tks

Check This Out!

More Links to Good Information