C# Helper functions to map a DataTable or DataRow to a class object

Posted on March 30, 2013 by Michael Roma

The following methods will allow you to map your DataTable, DataRow results to a class object.

Here are the helper functions:

// function that set the given object from the given data row
public static void SetItemFromRow(T item, DataRow row)
    where T : new()
    // go through each column
    foreach (DataColumn c in row.Table.Columns)
        // find the property for the column
        PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

        // if exists, set the value
        if (p != null && row[c] != DBNull.Value)
            p.SetValue(item, row[c], null);

// function that creates an object from the given data row
public static T CreateItemFromRow(DataRow row)
    where T : new()
    // create a new object
    T item = new T();

    // set the item
    SetItemFromRow(item, row);

    // return 
    return item;

// function that creates a list of an object from the given data table
public static List CreateListFromTable(DataTable tbl)
    where T : new()
    // define return list
    List lst = new List();

    // go through each row
    foreach (DataRow r in tbl.Rows)
        // add to the list

    // return the list
    return lst;

Here are examples on using these helper methods to map to your Customer class:

// get the list of customers in a data table
DataTable customerTable = GetCustomerTable(); // select * from customer

// map to a list of customers
List customerList = CreateListFromTable(customerTable);

// get a single customer in a data row
DataRow customerRow = GetSingleCustomer(3); // select * from customer where id = 3

// map to a customer
Customer customer = CreateItemFromRow(customerRow);
comments powered by Disqus