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: 184
Author: Mark Nugent Date Added: 11/26/2007
Copy Code  
1
2    /// <summary>

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

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

5    /// </summary>

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

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

12        /// </summary>

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

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

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

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

33        /// Adds a row to the DataTable.

34        /// </summary>

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

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

45            }
46            this.Rows.Add(newRow);
47        }
48    }
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);