Click here to Skip to main content
Click here to Skip to main content

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

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.

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.

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)

About the Author

kubben
Web Developer
United States United States
I started my programmer career over 18 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 both vb.net and C#. Lately I have been using VS2012 and writing a Windows 8 app. You can search for the app it is called ConvertIT.
 
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 Pinmembertoddmo4-May-12 10:48 
GeneralRe: A similar way that works for me Pinmemberkubben5-May-12 1:19 
QuestionProblem with DateTime value type Pinmemberfinalove8-Sep-11 15:29 
AnswerRe: Problem with DateTime value type Pinmemberkubben8-Sep-11 16:00 
GeneralRe: Problem with DateTime value type Pinmemberfinalove8-Sep-11 18:14 
Thx for replying me.
Im my C# project, the birthday field's type is SqlDateTime ( since it allows null value) and in SQL Server it's type is DateTime. Is it a problem ?
GeneralRe: Problem with DateTime value type Pinmemberkubben10-Sep-11 2:10 
GeneralMy vote of 5 Pinmembercham200822-Jun-11 7:51 
GeneralTraverse the properties instead of the columns collections to avoid runtime exceptions. Pinmemberckuroda2001@yahoo.com20-Jul-10 6:26 
GeneralRe: Traverse the properties instead of the columns collections to avoid runtime exceptions. Pinmemberkubben20-Jul-10 6:43 
Generalusing different data types during the conversion. Pinmemberckuroda2001@yahoo.com2-Jul-10 3:59 
GeneralRe: using different data types during the conversion. Pinmemberkubben2-Jul-10 5:08 
GeneralGreat code indeed PinmemberFabio CR19-Oct-09 9:58 
GeneralRe: Great code indeed Pinmemberkubben19-Oct-09 13:26 
GeneralGreat Code !!! Pinmemberyordan_georgiev6-Apr-09 7:04 
GeneralRe: Great Code !!! Pinmemberkubben6-Apr-09 7:10 
QuestionHow odd Pinmembericestatue31-Oct-06 13:16 
AnswerRe: How odd Pinmemberkubben31-Oct-06 13:33 
GeneralSa-weet! Pinmemberdotnethead10-May-06 4:26 
GeneralRe: Sa-weet! Pinmemberkubben10-May-06 9:31 
QuestionAm I missing Something? PinmemberBrian Leach11-Oct-05 6:41 
AnswerRe: Am I missing Something? Pinmemberkubben11-Oct-05 16:15 
GeneralCurrencyManager PinprotectorMarc Clifton9-Oct-05 15:25 
GeneralRe: CurrencyManager Pinmemberkubben9-Oct-05 16:57 
GeneralThis is wonderful... PinmemberDavid Kemp8-Oct-05 22:12 
GeneralRe: This is wonderful... Pinmemberkubben9-Oct-05 16:49 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 8 Oct 2005
Article Copyright 2005 by kubben
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid