This blog has moved!

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

<September 2008>
SuMoTuWeThFrSa
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011


Navigation

Professional Props...

Extracurricular Props...

Subscriptions

Article Categories



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 on Tuesday, March 23, 2004 12:06 PM by grant.killian





Powered by Dot Net Junkies, by Telligent Systems