Serializing class containing properties as DataTable.

I have made a method which can be used to serialize class (which contains only properties) into DataTable. All the properties and their conventional (C# data types) data types will be serialized as columns of datatable and their data types respectively.


using System.Reflection;

private DataTable GetTable(object obj)
{
Type objectType = obj.GetType();
PropertyInfo[] objectPropertyInfo = objectType.GetProperties();
DataTable table = new DataTable(objectType.Name);
DataColumn column;

for (int i = 0; i < objectPropertyInfo.Length; i++)
{
column = new DataColumn(objectPropertyInfo[i].Name, objectPropertyInfo[i].PropertyType);
table.Columns.Add(column);
}
return table;
}

Here “obj” is the object of class.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: