Ben's Random Mumbles

Passing SqlDataReader to Repeater OK?

I have made a post over at the asp.net forums about binding a SqlDataReader to a Repeater control but can't seem to get a straight answer. OK, I know I should be closing a DataReader when I'm finished with it, if I don't the connection doesn't get closed properly and after a while the web site will fall over.

But what about when you are binding a DataReader to a Repeater or DataList control? The DataReader is never closed, does the Repeater control handle this for me?

I have looked at 2 sample applications to see how they handle this, IBuySpyStore and the ASP.NET Forums. IBuySpy passes a SqlDataReader to the Repeater or DataList control, but the Forums read the data from the SqlDataReader into a collection of objects, close the DataReader and bind the collection to their control. Maybe I should be using the second technique, but I really like the simplicity of just binding a DataReader straight to a Repeater control.

Posted: Apr 01 2003, 07:48 PM by benricho | with 5 comment(s)
Filed under:

Comments

James Avery said:

I always try and explicitly close the reader, what if the repeater errors in the middle of binding?? The connection would be left open. Here is what I think you should do. Be sure and create the reader with the CommandBehavior.CloseConnection option.

SqlDataReader oReader;
try
{
oReader = MyDAL.GetReader();
MyRepeater.DataSource = oReader;
MyRepeater.DataBind();
}
catch
{
\\exception work here
}
finally
{
oReader.Close();
}

Or something like that.
# April 1, 2003 1:17 AM

Ben Richardson said:

Thanks James, I don't know why I didn't think of that.
# April 1, 2003 1:25 AM

Gauthier said:

Hello, I myself use the technique used in ASP.NET forum, because I only work with custom entities rather than DataSet and I prefer to at least have an abstraction layer between my presentational code (custom controls) and my Data Access code.

About the code snippet just on top of this comment, you would add a test to check if the datareader is not null:
IDataReader dr = null;
try
{
dr = SqlHelper.ExecuteReader(.......);
}
finally
{
if(dr != null) dr.Close();
}

I myself use the same approach in every of my DAL methods that use datareader, needless to say that I love DataAccess Application Block
# July 7, 2003 5:19 PM

Movenext and ASP.net | keyongtech said:

Pingback from  Movenext and ASP.net | keyongtech

# June 17, 2009 12:07 PM

cheinan said:

this is not good way of closing

you need to do:

MyRepeater.DataSource = MyDAL.GetReader();

MyRepeater.DataBind();

((OdbcDataReader)MyRepeater.DataSource).Close();

# August 25, 2011 6:02 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)