Home
Manage Your Code
Snippet: Convert an object's property values to a DataTable (C#)
Title: Convert an object's property values to a DataTable Language: C#
Description: By instantiating from an object, a DataTable instance is created that contains a column for each of the object's properties. Put simply, this class represents an object's class as a DataTable. Views: 343
Author: Mark Nugent Date Added: 11/26/2007
Copy Code  
1    /// <summary>

2    /// By instantiating from an object, a DataTable instance is created that contains a column for each 

3    /// of the object's properties.  Put simply, this class represents an object's class as a DataTable.

4    /// </summary>

5    public class ObjectPropertiesDataTable : System.Data.DataTable
6    {
7        private Type objectType = null;
8
9        /// <summary>

10        /// Initializes a new instance of the <see cref="ObjectPropertiesDataTable"/> class.

11        /// </summary>

12        /// <param name="obj">The object used to define the columns of the DataTable.

13        /// The DataTable object will contain a column for each of the object's properties.

14        /// A single row containing the values of the object's properties will be inserted in the table.</param>

15        public ObjectPropertiesDataTable(object obj) : base()
16        {
17            this.objectType = obj.GetType();
18            this.TableName = obj.GetType().Name;
19            InitializeColumns(obj);
20            AddRow(obj);
21        }
22
23        private void InitializeColumns(object obj)
24        {
25            foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
26            {
27                this.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
28            }
29        }
30
31        /// <summary>

32        /// Adds a row to the DataTable.

33        /// </summary>

34        /// <param name="obj">The object whose property values will be used to create the new row.</param>

35        public void AddRow(object obj)
36        {
37            if (obj.GetType() != this.objectType)
38                throw new ArgumentException("Object parameter's type must match object type used to instantiate class (" + this.objectType.FullName + ").");
39
40            DataRow newRow = this.NewRow();
41            foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
42            {
43                newRow[propertyInfo.Name] = obj.GetType().GetProperty(propertyInfo.Name).GetValue(obj, null); //(propertyInfo.PropertyType)

44            }
45            this.Rows.Add(newRow);
46        }
47    }
Usage
Employee emp1 = new Employee("John", "Smith");
Employee emp2 = new Employee("Jim", "Smith");
Employee emp3 = new Employee("Jan", "Smith");
ObjectPropertiesDataTable dt = new ObjectPropertiesDataTable(emp1);
dt.AddRow(emp2);
dt.AddRow(emp3);