List To DataTable and Vice Versa using C#

public class ObjectConverter
     public DataTable ListToDataTable(List items)
          DataTable dataTable = new DataTable(typeof(T).Name);
          //Get all the properties
          PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public |         BindingFlags.Instance);
          foreach (PropertyInfo prop in Props)
            //Setting column names as Property names
          foreach (T item in items)
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
               //inserting property values to datatable rows
               values[i] = Props[i].GetValue(item, null);
          return dataTable;

     public static List DataTableToList(DataTable dt)
       List lstdata = new List();
       foreach (DataRow row in dt.Rows)
           T item = GetItem(row);
        return lstdata;

      private static T GetItem(DataRow dr)
        Type temp = typeof(T);
        T obj = Activator.CreateInstance();

        foreach (DataColumn column in dr.Table.Columns)
          foreach (PropertyInfo pro in temp.GetProperties())
            if (pro.Name == column.ColumnName)
               pro.SetValue(obj, dr[column.ColumnName], null);
        return obj;
Calling : 
 ObjectConverter converter = new ObjectConverter();
 DataTable dtstudentDetails=new DataTable();
 dtstudentDetails = converter.ListToDataTable(lststudentDetails); 

 List lststudentDetails = new List(); 
 lststudentDetails = converter.DataTableToList(dtstudentDetails);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s