Click here to Skip to main content
15,891,704 members
Articles / Programming Languages / C#

Using Reflection to convert DataRows to objects or objects to DataRows

Rate me:
Please Sign up or sign in to vote.
3.65/5 (15 votes)
8 Oct 2005CPOL3 min read 128K   1.1K   34  
Using Reflection to convert DataRows to objects or objects to DataRows.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;

namespace ReflectIt
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class ReflectIt
	{
		#region Constructor
		public ReflectIt()
		{	
		}
		#endregion

		#region Load
		/// <summary>
		/// This function will populate the p_object passed in with the datarow passed in
		/// It is assumed that the datarow columns match exactly with the properties in the
		/// object passed in.
		/// </summary>
		/// <param name="p_dcc"></param>
		/// <param name="p_dr"></param>
		/// <param name="p_object"></param>
		public static void Load(DataColumnCollection p_dcc, DataRow p_dr, Object p_object)
		{
			Type t = p_object.GetType(); //This is used to do the reflection
			for (Int32 i=0;i<=p_dcc.Count -1;i++)
			{
				//Don't ask it just works
				try
				{  //NOTE the datarow column names must match exactly (including case) to the object property names
					t.InvokeMember(p_dcc[i].ColumnName  , BindingFlags.SetProperty , null, p_object, new object[] {p_dr[p_dcc[i].ColumnName]});
				}
				catch (Exception ex)
				{ //Usually you are getting here because a column doesn't exist or it is null
					if (ex.ToString() != null)
					{}
				}
			};//for i
		}
		#endregion

		#region ObjectToTableConvert
		/// <summary>
		/// This method takes in an object and by reflection takes the properties
		/// Creates a table if it doesn't already exist
		/// Adds a row to the table in a dataset.
		/// </summary>
		/// <param name="p_obj"></param>
		/// <param name="p_ds"></param>
		/// <param name="p_tableName"></param>
		public static void ObjectToTableConvert(Object p_obj, ref DataSet p_ds, String p_tableName)
		{
			//we need the type to figure out the properties
			Type t = p_obj.GetType();
			//Get the properties of our type
			PropertyInfo[] tmpP = t.GetProperties();
			
			//We need to create the table if it doesn't already exist
			if (p_ds.Tables[p_tableName] == null)
			{
				p_ds.Tables.Add(p_tableName);
				//Create the columns of the table based off the properties we reflected from the type
				foreach (PropertyInfo xtemp2 in tmpP) 
				{
					p_ds.Tables[p_tableName].Columns.Add(xtemp2.Name,xtemp2.PropertyType);
				} //foreach
			}
			//Now the table should exist so add records to it.
								
			Object[] tmpObj = new Object[tmpP.Length];
				
			for (Int32 i=0;i<=tmpObj.Length-1;i++)
			{
				//tmpObj[i] = tmpP[i].GetValue(p_obj,null);
				tmpObj[i] = t.InvokeMember(tmpP[i].Name  , BindingFlags.GetProperty, null, p_obj, new object[0]);

				
			}
			//Add the row to the table in the dataset
			p_ds.Tables[p_tableName].LoadDataRow(tmpObj,true);
		}
		#endregion
	}
	
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I started my programmer career over 26 years ago doing COBOL and SAS on a MVS mainframe. It didn't take long for me to move into windows programming. I started my windows programming in Delphi (Pascal) with a Microsoft SQL server back end. I started working with vb.net when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out asp.net in 2004. I achieved my MCSD.net in April 2005. I have done a lot of MS SQL database stuff. I have a lot of experience with Window Service and Web services as well. I spent three years as a consultant programing in C#. I really enjoyed it and found the switch between vb.net and C# to be mostly syntax. In my current position I am programming in C# working on WPF and MSSql database stuff. Lately I have been using VS2019.

On a personal note I am a born again Christian, if anyone has any questions about what it means to have a right relationship with God or if you have questions about who Jesus Christ is, send me an e-mail. ben.kubicek[at]netzero[dot]com You need to replace the [at] with @ and [dot] with . for the email to work. My relationship with God gives purpose and meaning to my life.

Comments and Discussions