views:

1432

answers:

4

I'm currently writing a C#-class in my ASP.NET (3.5) application to handle all database-queries. Some of the methods are there to make a select-query to the database. Inside the method i simply have a SqlDataReader r = command.ExecuteReader(); to fetch the data.

I now want r to be returned by the method, but when i close the database-connection, the datareader closes and the object contains nothing anymore. Thought of putting everything into a string-array, but this is unpractical if i have mixed integer and text-fields in my database. Is there an easy ("premade") way of storing the data in some object to return?

+3  A: 

You can use a datatable and SqlDataAdapter:

using(SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
  adap.fill(myDataTable);
}

return myDataTable;
scottm
or use the datatable load method - myDataTable.Load(myReader);
Russ Cam
A: 

you can just set the commandbehavior to closeconnection. and then when you call r.close the underlying connection will close.

willz
+1 to counter drive-by downvoter; this is a correct answer for the specific question, but of course the OP is using datareader incorrectly ;-)
Steven A. Lowe
+2  A: 

Typically, the results are either stuffed into a collection or a datatable. Datatables are a little easier from the perspective of not having to instantiate objects and storing them.

Chris Lively
+1  A: 

Have you thought of using Linq or an ORM like subsonic for this

Sam Saffron