Convert a DataReader to a DataTable

When working with Datareaders one of the problems i sometimes come across is binding these to 3rd party controls. A lot of controls will not bind to a DataReader but nearly all of the alwaays bind to a DataTable. All of the functionlity already exists in the Framework you just need to know where to look.

So here is the simple way to convert a DataReader to a DataTable.

Create a class Inheriting from DataAdapter

   class DataReaderAdapter : System.Data.Common.DataAdapter
    {
        public int FillFromReader(DataTable dataTable, IDataReader dataReader)
        {
            return this.Fill(dataTable, dataReader);
        }
    }

Then to use it :

DataReaderAdapter dar = new DataReaderAdapter();
dar.FillFromReader(dataTable, dataReader);

Attached is a sample project showing the use of this.

Author Greg Duffield

Greg has too many years experience in developement from VB for DOS all the way through to Windows Workflow and LINQ while covering pretty much every technology in between. A complete MS evangelist he is now Director of the only MS Gold Partner IT services company in Norfolk. Wehere they are producing Web 2 Applications for various sectors, and are currently entering the Haulage industry with their latest product.

Comments

SC said:

The example needs expanded to show how to implement the rest of the DataAdapter Interface - As it is, it just generates 4 compiler errors...

12/Jun/2007 08:40 AM

dazfitzg said:

You could of course use the simple DataTable.Load(IDataReader) function and save the creation of a class.

21/May/2009 15:59 PM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.