This blog has moved!

Check out www.CodeBetter.com/blogs/grant.killian

<July 2008>
SuMoTuWeThFrSa
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789


Navigation

Professional Props...

Extracurricular Props...

Subscriptions

Article Categories



Tuesday, March 23, 2004 - Posts

DataReader to DataTable sample code

Carlos, in a comment on my blog, requested the code I used in this post to efficiently convert a DataReader into a DataTable (it's inspired by Roy Osherove's post here and the comments to that post).  For posterity, I'm including the following example of how to extend the base DBDataAdapter class for fun and profit . . . I've formatted the most important code in bold.  This was a useful intermediary between a data access layer that delivered DataReaders and a business layer that worked with DataTables and DataSets.

//CustomAdapter Class
using System;
using System.Data;

namespace TheApplication.DataObjects
{
 public class CustomAdapter : System.Data.Common.DbDataAdapter
 {
  public int FillFromReader(DataTable dataTable, IDataReader dataReader)
  {
   return this.Fill( dataTable, dataReader );
  }

  protected override System.Data.Common.RowUpdatedEventArgs CreateRowUpdatedEvent( DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d )
  {
   return ( System.Data.Common.RowUpdatedEventArgs )new EventArgs();
  }
    
  protected override System.Data.Common.RowUpdatingEventArgs CreateRowUpdatingEvent( DataRow a, IDbCommand b, StatementType c, System.Data.Common.DataTableMapping d )
  {
   return ( System.Data.Common.RowUpdatingEventArgs )new EventArgs();
  }
  
  protected override void OnRowUpdated( System.Data.Common.RowUpdatedEventArgs value )
  {

  }
  protected override void OnRowUpdating( System.Data.Common.RowUpdatingEventArgs value )
  {

  } 
 }
}

And here is a plain vanilla sample usage of the class:

public static DataTable getDataTable( string sql )
  {
   DataTable dtOut = new DataTable();
   OdbcConnection cn = new OdbcConnection( ConnString() );
   cn.Open();
   OdbcCommand cmd = new OdbcCommand( sql, cn );
   IDataReader dr = cmd.ExecuteReader();

   CustomAdapter da = new CustomAdapter();
   da.FillFromReader( dtOut, dr ); //converts a datareader into a datatable
   cn.Close();
   return dtOut;
  }

Happy .Netting!

posted Tuesday, March 23, 2004 12:06 PM by grant.killian




Powered by Dot Net Junkies, by Telligent Systems