Click here to Skip to main content
15,881,898 members
Articles / Programming Languages / C#
Tip/Trick

Bind/Map DataTable to Object's Fields and Properties

Rate me:
Please Sign up or sign in to vote.
4.94/5 (14 votes)
27 Aug 2014CPOL 48.5K   32   12
Convert DataTable to Class Object

Lets take this DataTable as example:

C#
public DataTable GetTable()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Username");
    dt.Columns.Add("Level", typeof(int));

    dt.Rows.Add("John", 1);
    dt.Rows.Add("Cait", 2);

    return dt;
}

We want to bind/map/convert the DataTable into the following class:

C#
class Foo
{
    // Fields
    public string Username = "";

    // Properties
    public int Level { get; set; }
}

Bind DataTable to Object Class:

C#
DataTable dt = GetTable();
Foo foo = BindData<Foo>(dt);

Code behind:

C#
public T BindData<T>(DataTable dt)
{
    DataRow dr = dt.Rows[0];

    // Get all columns' name
    List<string> columns = new List<string>();
    foreach (DataColumn dc in dt.Columns)
    {
        columns.Add(dc.ColumnName);
    }

    // Create object
    var ob = Activator.CreateInstance<T>();

    // Get all fields
    var fields = typeof(T).GetFields();
    foreach (var fieldInfo in fields)
    {
        if (columns.Contains(fieldInfo.Name))
        {
            // Fill the data into the field
            fieldInfo.SetValue(ob, dr[fieldInfo.Name]);
        }
    }

    // Get all properties
    var properties = typeof(T).GetProperties();
    foreach (var propertyInfo in properties)
    {
        if (columns.Contains(propertyInfo.Name))
        {
            // Fill the data into the property
            propertyInfo.SetValue(ob, dr[propertyInfo.Name]);
        }
    }

    return ob;
}

Get a list of Objects from rows in a DataTable:

C#
List<Foo> lst = BindDataList<Foo>(dt);

Code behind:

C#
public List<T> BindDataList<T>(DataTable dt)
{
    List<string> columns = new List<string>();
    foreach (DataColumn dc in dt.Columns)
    {
        columns.Add(dc.ColumnName);
    }

    var fields = typeof(T).GetFields();
    var properties = typeof(T).GetProperties();

    List<T> lst = new List<T>();

    foreach (DataRow dr in dt.Rows)
    {
        var ob = Activator.CreateInstance<T>();

        foreach (var fieldInfo in fields)
        {
            if (columns.Contains(fieldInfo.Name))
            {
                fieldInfo.SetValue(ob, dr[fieldInfo.Name]);
            }
        }

        foreach (var propertyInfo in properties)
        {
            if (columns.Contains(propertyInfo.Name))
            {
                propertyInfo.SetValue(ob, dr[propertyInfo.Name]);
            }
        }

        lst.Add(ob);
    }

    return lst;
}

Above code is assuming that the DataType of DataColumn is equal to DataType of Fields and Properties. If they are not, like this:

C#
DataTable dt = new DataTable();
dt.Columns.Add("Level", typeof(string));

class Foo
{
    public int Level = 0;
}

The DataType of "Level" in the DataColumn is String, but it is Int in Class of Foo. Therefore, we need to take extra steps to verify and convert the data.

Below is one of the possible way to verify and convert the data:

In above example, we'll change this line:

C#
fieldInfo.SetValue(ob, dr[fieldInfo.Name]);

to this:

C#
if (fieldInfo.FieldType == typeof(int))
{
    int i = ExtractInt(dr[fieldInfo.Name]);
    fieldInfo.SetValue(ob, i);
}
else
{
    fieldInfo.SetValue(ob, dr[fieldInfo.Name]);
}

Method of ExtractInt()

C#
public int ExtractInt(object data)
{
    if (data.GetType() == typeof(int))
    {
        return (int)data;
    }
    else
    {
        int i = 0;
        int.TryParse(data + "", out i);
        return i;
    }
}

Happy coding

License

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


Written By
Software Developer
Other Other
Programming is an art.

Comments and Discussions

 
QuestionCool Pin
NewValeria21-May-16 1:04
NewValeria21-May-16 1:04 
GeneralExcelente funcionamiento justo lo que buscaba Pin
sauryjorge13-Jan-16 6:30
sauryjorge13-Jan-16 6:30 
SuggestionSuggested improvements Pin
Sebastien GASPAR1-Sep-14 1:52
Sebastien GASPAR1-Sep-14 1:52 
GeneralRe: Suggested improvements Pin
adriancs1-Sep-14 3:27
mvaadriancs1-Sep-14 3:27 
General5 vote.. perfect timing Pin
KLPounds29-Aug-14 11:29
KLPounds29-Aug-14 11:29 
QuestionMy vote of 5 Pin
FernandoUY28-Aug-14 17:12
professionalFernandoUY28-Aug-14 17:12 
QuestionWhat's the advantage over Entity Framework? Pin
leiyangge28-Aug-14 4:32
leiyangge28-Aug-14 4:32 
Your framework looks like some kind of ORM, am I right? What's the advantage over Entity Framework?
Besides, what benefit will it add to use properties instead of columns, if it is the simple case of the example?
Did you try DynamicObject .net 4.0?
AnswerRe: What's the advantage over Entity Framework? Pin
adriancs29-Aug-14 0:59
mvaadriancs29-Aug-14 0:59 
GeneralRe: What's the advantage over Entity Framework? Pin
leiyangge29-Aug-14 5:37
leiyangge29-Aug-14 5:37 
GeneralRe: What's the advantage over Entity Framework? Pin
adriancs29-Aug-14 13:13
mvaadriancs29-Aug-14 13:13 
GeneralRe: What's the advantage over Entity Framework? Pin
leiyangge29-Aug-14 23:10
leiyangge29-Aug-14 23:10 
GeneralMy vote of 5 Pin
Volynsky Alex27-Aug-14 13:21
professionalVolynsky Alex27-Aug-14 13:21 

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.