How can I convert a DataSet to a DataReader?
-
2I feel there is a flaw in what you are trying to do. What ARE you trying to do at a higher level? – Dan Aug 20 '10 at 09:56
-
You can't. If you want more explanation, please provide more information. – Thorsten Dittmar Aug 20 '10 at 09:47
6 Answers
You can use the following code to change dataset to DataReader
:
DataTableReader rd = ds.Tables[0].CreateDataReader();

- 4,119
- 1
- 22
- 32

- 457
- 5
- 16
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

- 54,530
- 11
- 89
- 103
DataSet
has a method called CreateDataReader
which will create a DataTableReader
, but I don't think that you can create a DataReader
.

- 47,437
- 25
- 129
- 188
DataSet is a disconnected in-memory object. DataReader is a connected unidirectional object.
So I guess it is not possible.
Is it really needed?

- 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
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
}

- 98,240
- 88
- 296
- 433
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.

- 6,099
- 4
- 26
- 41