Click here to Skip to main content
15,885,244 members
Articles / Programming Languages / C#
Article

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 127.8K   1.1K   34   25
Using Reflection to convert DataRows to objects or objects to DataRows.

Sample Image - ReflectitTestApp.gif

Introduction

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.

Background

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.

C#
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
        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
}

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.

C#
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] = 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);
}

Conclusion

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.

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

 
SuggestionA similar way that works for me Pin
toddmo4-May-12 10:48
toddmo4-May-12 10:48 
GeneralRe: A similar way that works for me Pin
kubben5-May-12 1:19
kubben5-May-12 1:19 
QuestionProblem with DateTime value type Pin
finalove8-Sep-11 15:29
finalove8-Sep-11 15:29 
AnswerRe: Problem with DateTime value type Pin
kubben8-Sep-11 16:00
kubben8-Sep-11 16:00 
GeneralRe: Problem with DateTime value type Pin
finalove8-Sep-11 18:14
finalove8-Sep-11 18:14 
GeneralRe: Problem with DateTime value type Pin
kubben10-Sep-11 2:10
kubben10-Sep-11 2:10 
GeneralMy vote of 5 Pin
cham200822-Jun-11 7:51
cham200822-Jun-11 7:51 
GeneralTraverse the properties instead of the columns collections to avoid runtime exceptions. Pin
ckuroda2001@yahoo.com20-Jul-10 6:26
ckuroda2001@yahoo.com20-Jul-10 6:26 
GeneralRe: Traverse the properties instead of the columns collections to avoid runtime exceptions. Pin
kubben20-Jul-10 6:43
kubben20-Jul-10 6:43 
Generalusing different data types during the conversion. Pin
ckuroda2001@yahoo.com2-Jul-10 3:59
ckuroda2001@yahoo.com2-Jul-10 3:59 
GeneralRe: using different data types during the conversion. Pin
kubben2-Jul-10 5:08
kubben2-Jul-10 5:08 
GeneralGreat code indeed Pin
Fabio CR19-Oct-09 9:58
Fabio CR19-Oct-09 9:58 
GeneralRe: Great code indeed Pin
kubben19-Oct-09 13:26
kubben19-Oct-09 13:26 
GeneralGreat Code !!! Pin
yordan_georgiev6-Apr-09 7:04
yordan_georgiev6-Apr-09 7:04 
GeneralRe: Great Code !!! Pin
kubben6-Apr-09 7:10
kubben6-Apr-09 7:10 
QuestionHow odd Pin
icestatue31-Oct-06 13:16
icestatue31-Oct-06 13:16 
AnswerRe: How odd Pin
kubben31-Oct-06 13:33
kubben31-Oct-06 13:33 
GeneralSa-weet! Pin
Brent Lamborn10-May-06 4:26
Brent Lamborn10-May-06 4:26 
GeneralRe: Sa-weet! Pin
kubben10-May-06 9:31
kubben10-May-06 9:31 
QuestionAm I missing Something? Pin
Brian Leach11-Oct-05 6:41
Brian Leach11-Oct-05 6:41 
AnswerRe: Am I missing Something? Pin
kubben11-Oct-05 16:15
kubben11-Oct-05 16:15 
GeneralCurrencyManager Pin
Marc Clifton9-Oct-05 15:25
mvaMarc Clifton9-Oct-05 15:25 
GeneralRe: CurrencyManager Pin
kubben9-Oct-05 16:57
kubben9-Oct-05 16:57 
GeneralThis is wonderful... Pin
David Kemp8-Oct-05 22:12
David Kemp8-Oct-05 22:12 
GeneralRe: This is wonderful... Pin
kubben9-Oct-05 16:49
kubben9-Oct-05 16: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.