posts - 25, comments - 24, trackbacks - 0

My Links

News

Archives

Post Categories

Tuesday, May 26, 2009

Return SqlDataReader from a method

.NET's SqlDataReader class is based on an active connection to the database. This means that while the SqlDataReader is in use, the SqlConnection that is serving the SqlDataReader is open and cannot be used anywhere else.

That is why, returning an SqlDataReader from a method is not stright forward like returning a DataTable or a DataSet. To read more about SqlDataReader, please see SqlDataReader class.

Though it is not straight forward, it is very simple. Here's a piece of code that would let you return a SqlDataReader from a method:

public SqlDataReader GetData(string item1, string item2)
{
    SqlDataReader reader = null;
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        SqlCommand command = new SqlCommand();
        command.CommandType = CommandType.StoredProcedure;
       command.CommandText = "YOUR_SPROC_NAME";
       command.Parameters.Add("@Item1", SqlDbType.VarChar, 255).Value = item1;
       command.Parameters.Add("@Item2", SqlDbType.VarChar, 255).Value = item2;
        command.Connection = connection;
        connection.Open();
        reader = command.ExecuteReader(CommandBehavior.CloseConnection);
    }
    catch (Exception ex)
    {
        connection.Close();
       Response.Write(ex.Message);
    }
    return reader;

}

posted @ Tuesday, May 26, 2009 1:58 AM | Feedback (0) | Filed Under [ C# ASP.NET ]

Powered by: