6

How can I convert a DataSet to a DataReader?

NakedBrunch
  • 48,713
  • 13
  • 73
  • 98
anjum
  • 2,363
  • 6
  • 28
  • 25

6 Answers6

15

You can use the following code to change dataset to DataReader:

DataTableReader rd = ds.Tables[0].CreateDataReader();
Michał Z.
  • 4,119
  • 1
  • 22
  • 32
5

Both DataSet and DataTable expose a method CreateDataReader which creates a DataTableReader. Check these links -

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

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

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
0

DataSet has a method called CreateDataReader which will create a DataTableReader, but I don't think that you can create a DataReader.

DataSet.CreateDataReader

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
0

DataSet is a disconnected in-memory object. DataReader is a connected unidirectional object.

So I guess it is not possible.

Is it really needed?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • https://msdn.microsoft.com/en-us/library/system.data.common.dbdatareader(v=vs.110).aspx - Reads a forward-only stream of rows from a data source. Says nothing about being 'Connected' to a database. – JJS Dec 02 '15 at 17:59
0

If you want to iterate thru DataSet, you don't need a DataReader. DataSet is a disconnected in-memory object so iterate thru it using for-each:

foreach(var row in ds.Tables["YourTable"])
{
     var value = row.Field<int>("ID"); // etc
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

You cannot convert a DataSet to a DbDataReader.

You can however create a DbDataReader that will read results from the DataSet by calling the CreateDataReader method on the DataSet.

However, this seems like a strange thing to want to do. You can simply iterate through the results contained in the DataSet using the Tables property of DataSet and The Rows property of DataTable. Using a DbDataReader would restrict you to forward only access to the results. The only benefit I can see from using a DbDataReader would be if you had an API call to make which required one as a parameter.

If your DataSet is the result of a SELECT command from a database, you should be able to get a DbDataReader by calling DbCommand.ExecuteReader(). This will cut out the DataSet altogether and result in something that is more efficient.

Alex Humphrey
  • 6,099
  • 4
  • 26
  • 41