posts - 25, comments - 21, trackbacks - 0

My Links

News

Archives

Post Categories

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;

}

Print | posted on Tuesday, May 26, 2009 1:58 AM | Filed Under [ C# ASP.NET ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: