Dynamically Create a DataTable from the Properties of a Custom Class

This C# example shows how to create a DataTable based on the Properties of a custom class and then fill the DataTable with data derived from a List<CustomClass> of custom class objects.

In this example we have a List of Person objects that we would like to fill into a DataTable object. We could manually create a DataTable with Column names that match Person Properties, but we want to show how this can be done dynamically using Reflection

Summary of the code:
In the code below, we have a class named Person which contains the Properties: Name, Birthday, Email, and FavoriteColor. In addition to the Properties, the Person class has a method that simply generates a List of Person objects.

The Main() code will get the List of Person objects and then dynamically create a DataTable that resembles the Person class. To make the DataTable resemble the Person class, we will use System.Reflection to determine the name of the Properties of the Person class and then use those names to generate the Column names of the DataTable. In other words, the DataTable will contain Columns that have the same names as the names of the Properties of the Person class.

Next, we loop through the List of Person objects and add each Person item into a new DataRow of the DataTable. So, each item in the List of Person objects will end up being a DataRow within the DataTable.

Finally, we will loop through the DataTable rows and print out the the values of each Column of each DataRow.

    1 using System;

    2 using System.Collections.Generic;

    3 

    4 namespace ConsoleApplication

    5 {

    6     class Program

    7     {

    8         static void Main()

    9         {

   10             // Create a list of Person objects

   11             List<Person> people = Person.GetPeople();

   12 

   13             // Dynamically create a DataTable based on the Properties of the Person class

   14             Type person = typeof(Person);

   15             System.Reflection.PropertyInfo[] properties = person.GetProperties();

   16             System.Data.DataTable dt = new System.Data.DataTable();

   17             foreach (System.Reflection.PropertyInfo pi in properties)

   18             {

   19                 dt.Columns.Add(pi.Name);

   20             }

   21 

   22             // Add the Person objects to the DataTable – Each Person item equals a new DataRow

   23             foreach (Person p in people)

   24             {

   25                 System.Data.DataRow dr = dt.NewRow();

   26                 foreach (System.Reflection.PropertyInfo pi in properties)

   27                 {

   28                     dr[pi.Name] = pi.GetValue(p, null);

   29                 }

   30 

   31                 dt.Rows.Add(dr);

   32             }

   33 

   34             foreach (System.Data.DataRow dr in dt.Rows)

   35             {

   36                 Console.WriteLine("\r\n******************************\r\nName: {0}\r\nBirtday: {1}\r\nEmail: {2}\r\nFavorite Color: {3}\r\n******************************\r\n", dr["Name"], dr["Birthday"], dr["Email"], dr["FavoriteColor"]);

   37             }

   38             Console.ReadLine();

   39         }

   40 

   41         // This is our custom class

   42         class Person

   43         {

   44             public enum Color

   45             {

   46                 Black,

   47                 Blue,

   48                 Red,

   49                 Yellow,

   50                 White

   51             }

   52 

   53             public string Name { get; set; }

   54             public DateTime Birthday { get; set; }

   55             public string Email { get; set; }

   56             public Color FavoriteColor { get; set; }

   57 

   58             // Create a generic List of Person objects

   59             public static List<Person> GetPeople()

   60             {

   61                 List<Person> people = new List<Person>();

   62                 Person p1 = new Person { Birthday = DateTime.Now.AddDays(-10513), Email = "manny@jedej.com", FavoriteColor = Person.Color.Black, Name = "Manny" };

   63                 Person p2 = new Person { Birthday = DateTime.Now.AddDays(-2546), Email = "moe@jedej.com", FavoriteColor = Person.Color.Blue, Name = "Moe" };

   64                 Person p3 = new Person { Birthday = DateTime.Now.AddDays(-10256), Email = "jack@jedej.com", FavoriteColor = Person.Color.Red, Name = "Jack" };

   65                 people.AddRange(new Person[] { p1, p2, p3 });

   66                 return (people);

   67             }

   68         }

   69     }

   70 }

   71 

Output:

******************************
Name: Manny
Birtday: 10/8/1982 5:06:03 PM
Email: manny@jedej.com
Favorite Color: Black
******************************
******************************
Name: Moe
Birtday: 7/31/2004 5:06:03 PM
Email: moe@jedej.com
Favorite Color: Blue
******************************
******************************
Name: Jack
Birtday: 6/22/1983 5:06:03 PM
Email: jack@jedej.com
Favorite Color: Red
******************************

Advertisements

2 thoughts on “Dynamically Create a DataTable from the Properties of a Custom Class

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s