Click here to Skip to main content
13,248,087 members (35,587 online)
Click here to Skip to main content
Add your own
alternative version


34 bookmarked
Posted 8 Oct 2005

Using Reflection to convert DataRows to objects or objects to DataRows

, 8 Oct 2005
Rate this:
Please Sign up or sign in to vote.
Using Reflection to convert DataRows to objects or objects to DataRows.

Sample Image - ReflectitTestApp.gif


Sometimes you need to populate an object (class) from a DataSet. If you only have one record in your table then you can use serialization to populate your class. The issue comes when you have multiple records in your table. This is where serialization doesn't work as well. So using reflection you can see what is in the DataRow and match it up with the property in your object (class). Sometimes you want to go the other way. So I also wrote an object to DataSet conversion using reflection.


We had some existing code that takes one DataRow in a table in a dataset, puts the DataSet into XML and then deserializes the XML into the object (class). The problem is that it only works on one record. We had the need to load hundreds of DataRows into objects. So instead of requesting each row and de-serializing the XML, I wrote a method that uses reflection to check what was in the DataRow and find the matching property in the object. Note these are simple objects, i.e. there are no sub collections or arrays in them, so it is pretty much just a bunch of properties. It is a one table to one object.

Next we had a collection of objects that had been processed and needed to be written out into a DataSet for reporting. So again I used reflection to figure out the properties and create the columns in the DataSet table. Note these are simple objects so there isn't any processing of sub collections or arrays inside of the object. I suppose this could be a future enhancement.

Load Method

I created a Load method that takes the list of columns in the DataRow, the DataRow itself and the object (class). Once the type of the object is determined then we use the InvokeMember to reflect the DataRow column into the property. Note it is important that the properties and the data column names match case. If the case does not match or if the column is null or if the column doesn't exist as a property, you will get an exception.

public static void Load(DataColumnCollection p_dcc, 
       DataRow p_dr, Object p_object)
        //This is used to do the reflection
    Type t = p_object.GetType();     
        for (Int32 i=0;i<=p_dcc.Count -1;i++)
        //Don't ask it just works
//NOTE the datarow column names must match exactly 
//(including case) to the object property names
            t.InvokeMember(p_dcc[i].ColumnName  , 
                          BindingFlags.SetProperty , null, 
                          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

ObjectToTableConvert Method

Next I created an object to table conversion method. You pass in the object, and the DataSet you want the table/DataRow to be added to, and the table name. There is a little more going on here. First we have to check to see if the table is already in the DataSet. If it is not then we create it and use reflection on the object to create the columns of the table. Then we use an object array to load each of the properties of the object. Then we can load the object array in to the table in the DataSet.

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)
        //Create the columns of the table based off the 
        //properties we reflected from the type
        foreach (PropertyInfo xtemp2 in tmpP) 
        } //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] = t.InvokeMember(tmpP[i].Name  , 
                              BindingFlags.GetProperty, null,
                              p_obj, new object[0]);
    //Add the row to the table in the dataset


There isn't a lot of code here, but I have found it helpful in converting DataRows to objects or objects back into tables and DataSets. I think this is one case where reflection works pretty well. I have included a test app that uses the Northwind SQL Server database so you can check it out for yourself.


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


About the Author

Software Developer (Senior)
United States United States
I started my programmer career over 21 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 when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out in 2004. I achieved my 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 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 VS2015.

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.

You may also be interested in...


Comments and Discussions

SuggestionA similar way that works for me Pin
toddmo4-May-12 11:48
membertoddmo4-May-12 11:48 
GeneralRe: A similar way that works for me Pin
kubben5-May-12 2:19
memberkubben5-May-12 2:19 
QuestionProblem with DateTime value type Pin
finalove8-Sep-11 16:29
memberfinalove8-Sep-11 16:29 
AnswerRe: Problem with DateTime value type Pin
kubben8-Sep-11 17:00
memberkubben8-Sep-11 17:00 
You know it has been a while since I have used this code. There are some issues with nulls or dbnull from a table and an object that doesn't support null. Since you can have types in your object that are nullable types, that is what I would suggest. You may need to check to see if the database field is null before you try to set it.

GeneralRe: Problem with DateTime value type Pin
finalove8-Sep-11 19:14
memberfinalove8-Sep-11 19:14 
GeneralRe: Problem with DateTime value type Pin
kubben10-Sep-11 3:10
memberkubben10-Sep-11 3:10 
GeneralMy vote of 5 Pin
cham200822-Jun-11 8:51
membercham200822-Jun-11 8:51 
GeneralTraverse the properties instead of the columns collections to avoid runtime exceptions. Pin
ckuroda2001@yahoo.com20-Jul-10 7:26
memberckuroda2001@yahoo.com20-Jul-10 7:26 
GeneralRe: Traverse the properties instead of the columns collections to avoid runtime exceptions. Pin
kubben20-Jul-10 7:43
memberkubben20-Jul-10 7:43 
Generalusing different data types during the conversion. Pin
ckuroda2001@yahoo.com2-Jul-10 4:59
memberckuroda2001@yahoo.com2-Jul-10 4:59 
GeneralRe: using different data types during the conversion. Pin
kubben2-Jul-10 6:08
memberkubben2-Jul-10 6:08 
GeneralGreat code indeed Pin
Fabio CR19-Oct-09 10:58
memberFabio CR19-Oct-09 10:58 
GeneralRe: Great code indeed Pin
kubben19-Oct-09 14:26
memberkubben19-Oct-09 14:26 
GeneralGreat Code !!! Pin
yordan_georgiev6-Apr-09 8:04
memberyordan_georgiev6-Apr-09 8:04 
GeneralRe: Great Code !!! Pin
kubben6-Apr-09 8:10
memberkubben6-Apr-09 8:10 
QuestionHow odd Pin
icestatue31-Oct-06 14:16
membericestatue31-Oct-06 14:16 
AnswerRe: How odd Pin
kubben31-Oct-06 14:33
memberkubben31-Oct-06 14:33 
GeneralSa-weet! Pin
dotnethead10-May-06 5:26
memberdotnethead10-May-06 5:26 
GeneralRe: Sa-weet! Pin
kubben10-May-06 10:31
memberkubben10-May-06 10:31 
QuestionAm I missing Something? Pin
Brian Leach11-Oct-05 7:41
memberBrian Leach11-Oct-05 7:41 
AnswerRe: Am I missing Something? Pin
kubben11-Oct-05 17:15
memberkubben11-Oct-05 17:15 
GeneralCurrencyManager Pin
Marc Clifton9-Oct-05 16:25
protectorMarc Clifton9-Oct-05 16:25 
GeneralRe: CurrencyManager Pin
kubben9-Oct-05 17:57
memberkubben9-Oct-05 17:57 
GeneralThis is wonderful... Pin
David Kemp8-Oct-05 23:12
memberDavid Kemp8-Oct-05 23:12 
GeneralRe: This is wonderful... Pin
kubben9-Oct-05 17:49
memberkubben9-Oct-05 17:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 8 Oct 2005
Article Copyright 2005 by kubben
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid