Expose a DataTableReader from a DataTable or from a DataSet

As DataReaders were ideal to read information from a connected database quickly (in a read-only, forward-only manner), DataTableReader does the same for your disconnected DataTables. The magic words (which I can’t underpin enough) are read-only, forward-only.

You work with the DataTableReader exactly the same way as you’ve done with DataReaders. The main difference is instantiation. You need to call the CreateDataReader method of a DataSet or a DataTable. When you call the DataSet method, you have the opportunity to pass an unspecified number of DataTable instances as parameter (with the help of the params keyword). Then you can call the NextResult method of DataTableReader to jump to the next table.

An example of how to do it:

DataTable myTable = new DataTable(“MyLittleTable);
SqlDataAdapter myAdapter = new SqlDataAdapter(aValidSqlCommand);
DataTableReader theReader = myTable.CreateDataReader();
for(int i=0; i<theReader.FieldCount; i++)
Console.WriteLine({0}: {1}”, i, theReader.GetValue(i));

As you can see, the DataTableReader doesn’t need a connection to any data source, because it reads data from a disconnected table. The iteration and the whole structure of the DataTableReader is the same as the DataReader, you have the same GetXxx methods and the well-known Read and NextResult is at hand, too.

A quick review: DataTableReader is a forward-only, read-only cursor for iterating over information stored in DataSets and DataTables, as quick as possible. Use it when you need results fast, and don’t need to modify data during iteration.


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: