Here we are going to convert Generic List to datatable in c#.
Creating a simple Employee class following below:
public class Employee
{
public string Name { get; set; }
public int EmpId { get; set; }
public int salary { get; set; }
}
And a List with some data following below:
List<Employee> Employee = new List<Employee>(){
new Employee() { Name = "Pawan", salary = 15000, EmpId = 100 },
new Employee() { Name = "rajeev", salary = 25000, EmpId = 101},
new Employee() { Name = "John", salary = 21000, EmpId = 102 }
};
Create a method that will convert any type of Generic List to a DataTable.
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties by using reflection
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{ //Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items) {
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
To call the “ToDataTable” method on button Click, use the following Code:
List<Employee> Employee = new List<Employee>(){ new Employee() { Name = "Pawan", salary = 15000, EmpId = 100 },
new Employee() { Name = "rajeev", salary = 25000, EmpId = 101},
new Employee() { Name = "John", salary = 21000, EmpId = 102 }
};
DataTable dt = ToDataTable(Employee);
Example :
protected void btnConvertDatatableToList_Click(object sender, EventArgs e)
{
List<Employee> Employee = new List<Employee>(){
new Employee() { Name = "Pawan", salary = 15000, EmpId = 100 },
new Employee() { Name = "rajeev", salary = 25000, EmpId = 101},
new Employee() { Name = "John", salary = 21000, EmpId = 102 }
};
DataTable dt = ToDataTable(Employee);
}
I hope it will help to you.
Liked By
Write Answer
how to Convert Generic List to DataTable in c#
Join MindStick Community
You have need login or register for voting of answers or question.
Anonymous User
01-Dec-2020Here we are going to convert Generic List to datatable in c#.
Creating a simple Employee class following below:
And a List with some data following below:
Create a method that will convert any type of Generic List to a DataTable.
To call the “ToDataTable” method on button Click, use the following Code:
Example :
I hope it will help to you.