Monday, December 7, 2015

Create DataTable from List in C#

T is type of Class which you want convert i.e. T = Class Name

 public static DataTable ConvertToDataTable<T>(List<T> data)
 {
            //Create property description collection object of you table type object
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();

           //Bind object field as header row of DataTable
            foreach (PropertyDescriptor prop in properties)
            {
                table.Columns.Add(prop.Name, typeof(string));
            }

            //Bind data of list into DataTable
            foreach (T item in data)
            {
                //Create dataRow object for Table
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                {
                   //Assign list value into dataTable column
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                }
                table.Rows.Add(row);
            }
         
           //return DataTable object
            return table;
 }