Question

I have a function that populates an object using IDataReader:

private void FillDataItem(IDataReader datareader)
{
    this.CompanyCode = datareader.GetString(datareader.GetOrdinal("COMPANY"));
    this.Name = datareader.GetString(datareader.GetOrdinal("NAME"));
    //...and so on
}

This is very useful when using an SqlDataReader to populate an object's fields based on the results of an SQL query. Pretty much all of my classes have this kind of "FillDataItem" that takes an IDataReader. Makes bringing database objects into the code ridiculously easy.

However, now I want to do the same thing, but with a DataRow from a DataTable as the data source. The situation is that am presented with a custom built DataTable that is in the exact same format (same columns) as if it were from an SQL query, but it's not from any external data source like that. I want to loop through the rows of the DataTable, and with each row, fill an object in the same way as the above FillDataItem() method.

Of course I can just create an overloaded new method that takes the DataRow as the parameter:

private void FillDataItem(DataRow datarow)
{
    this.CompanyCode = datarow["COMPANY"].ToString();
    this.Name = datarow["NAME"].ToString();
    //...and so on
}

But that is so similar to the IDataReader version, that I would really like to know how I can get achieve my goal in one method so that such similar code doesn't need to be duplicated. Considering that I have a lot of fields, the FillDataItem method is like 200 lines long. To copy/paste this into a DataRow version seems wasteful and hard to maintain.

Was it helpful?

Solution

There is a CreateDataReader method on the datatable. You can use that an pass the datareader to your existing code.

http://msdn.microsoft.com/en-us/library/system.data.datatable.createdatareader.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top