Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind SqlDataReader to Repeater. Good practice?

Tags:

c#

.net

asp.net

Is this a good practice and is there anything I need to look out for? I was binding repeater to an asp:SqlDataSource. Primary reason for doing this is to gain more control of the SqlCommand (e.g. CommandTimeout).

Example:

    try
    {
        SqlDataReader MyReader = GetSomeResultsFromSqlCommand();
        MyRepeater.DataSource = MyReader;
        MyRepeater.DataBind();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        MyReader.Close();
    }
like image 458
Eddie Avatar asked Dec 02 '22 07:12

Eddie


2 Answers

This is a perfectly fine thing to do - let me offer a more succinct syntax that will provide the same results and offer the same fail-safe cleanup abilities:

using (SqlDataReader MyReader = GetSomeResultsFromSqlCommand())
{
    MyRepeater.DataSource = MyReader;
    MyRepeater.DataBind();
}
like image 92
Andrew Hare Avatar answered Dec 22 '22 10:12

Andrew Hare


Your code seems to be OK as written and does not necessarily appear to violate any best practices. You could however redactor the code a bit and utilize the "using" statement instead of the try, catch, finally...


I personally try to avoid using the SqlDataSource as it tightly couples your front end code to your data. To keep separation of concerns, I'd create a function within a class that can get this data for you and can be customized as much as needed.
like image 25
RSolberg Avatar answered Dec 22 '22 11:12

RSolberg