C-Sharp Converting List Generic into DataTable

In this article, we will learn c# datatable, c# list and generic collection in c#, How we can convert an List object into DataTable. Sometimes we works with two types of code standards one Entity Framework (EF) and another Ado.net. In case of EF Model we deals with List Generics and in case of ADO.net we mostly deals with DataTable.

So sometimes we needs to face challenge to convert List generic object into DataTable and vice versa.

To do this we needs to import System.Collections.Generic namespace for List Collection. System.Data namespace for DataTable and System.Reflection namespace for getting runtime properties over List object.

Step 1: Open Visual Studio and create Console Application and add all required namespaces.

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

Step 2: Create simple student Data Transfer Object(DTO) Class Model StudentDTO

public class StudentDTO { public int StudentId { get; set; } public int RollNo { get; set; } public string ClassName { get; set; } public string Sectionname { get; set; } public string SessionName { get; set; } public string StudentName { get; set; } }

Step 3: create an Business object to get Some collection with data.

public static class StudentBAL { public static IEnumerable GetStudents() { List li = new List(); List n = new List(); n.Add("Jack"); n.Add("Maria"); n.Add("Wiliam"); n.Add("Rock"); n.Add("Marina"); n.Add("Harish"); n.Add("Jhon"); n.Add("Raidu"); int i = 1; foreach (string s in n) { li.Add(new StudentDTO() { ClassName = "6th", RollNo = i, Sectionname = "A", SessionName = "2019-2020", StudentId = i + 100, StudentName = s }); i++; } return li; } }

Step 4: Getting List of students.

IEnumerable stu = StudentBAL.GetStudents(); // Uncomment to print entire collection //foreach(StudentDTO s in stu) // Console.WriteLine($"StudentId: {s.StudentId} StudentName: {s.StudentName}");

Step 5: Create DataTable object.

//Creates DataTable Object DataTable dt = new DataTable("Students");

We can add DataColumns to map properties of StudentDTO in two ways statically and dynamically using reflection.

dt.Columns.Add("StudentId", Type.GetType("System.Int32")); dt.Columns.Add("RollNo", Type.GetType("System.Int32")); dt.Columns.Add("ClassName"); dt.Columns.Add("Sectionname"); dt.Columns.Add("SessionName"); dt.Columns.Add("StudentName"); // OR Type t = typeof(StudentDTO); PropertyInfo[] propInfos = t.GetProperties(); foreach (PropertyInfo p in propInfos) dt.Columns.Add(new DataColumn() { ColumnName = p.Name, DataType = p.PropertyType });

Step 6: Populating DataTable with rows(Data).

foreach (StudentDTO s in stu) dt.Rows.Add(s.StudentId, s.RollNo, s.ClassName, s.Sectionname, s.SessionName, s.StudentName);

Step 7: Retrieving data from DataTable.

foreach (DataRow r in dt.Rows) { Console.WriteLine("========================================="); foreach (DataColumn c in dt.Columns) { Console.WriteLine($"{c.ToString()}: {r[c.ToString()]}"); } }

The entire program for converting List object into DataTable as follows.

using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace ConsoleApplication { public class StudentDTO { public int StudentId { get; set; } public int RollNo { get; set; } public string ClassName { get; set; } public string Sectionname { get; set; } public string SessionName { get; set; } public string StudentName { get; set; } } public static class StudentBAL { public static IEnumerable GetStudents() { List li = new List(); List n = new List(); n.Add("Jack"); n.Add("Maria"); n.Add("Wiliam"); n.Add("Rock"); n.Add("Marina"); n.Add("Harish"); n.Add("Jhon"); n.Add("Raidu"); int i = 1; foreach (string s in n) { li.Add(new StudentDTO() { ClassName = "6th", RollNo = i, Sectionname = "A", SessionName = "2019-2020", StudentId = i + 100, StudentName = s }); i++; } return li; } } class Program { static void Main(string[] args) { IEnumerable stu = StudentBAL.GetStudents(); // Uncomment to print entire collection //foreach(StudentDTO s in stu) // Console.WriteLine($"StudentId: {s.StudentId} StudentName: {s.StudentName}"); //Creates DataTable Object DataTable dt = new DataTable("Students"); //Create Static Columns for DataTable //dt.Columns.Add("StudentId", Type.GetType("System.Int32")); //dt.Columns.Add("RollNo", Type.GetType("System.Int32")); //dt.Columns.Add("ClassName"); //dt.Columns.Add("Sectionname"); //dt.Columns.Add("SessionName"); //dt.Columns.Add("StudentName"); //Creates Dynamic Columns for DataTable Type t = typeof(StudentDTO); PropertyInfo[] propInfos = t.GetProperties(); foreach (PropertyInfo p in propInfos) dt.Columns.Add(new DataColumn() { ColumnName = p.Name, DataType = p.PropertyType }); //Inserting Data for DataTable foreach (StudentDTO s in stu) dt.Rows.Add(s.StudentId, s.RollNo, s.ClassName, s.Sectionname, s.SessionName, s.StudentName); //Retrive Data From DataTable foreach (DataRow r in dt.Rows) { Console.WriteLine("========================================="); foreach (DataColumn c in dt.Columns) { Console.WriteLine($"{c.ToString()}: {r[c.ToString()]}"); } } Console.ReadKey(); } } }

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories