I am trying to read from datareader but i am gettin the error “Invalid attempt to call Read when reader is closed.” The stored procedure is working fine but when i try to read fom datareader it throws error.Plz help me
protected void CheckDatabase()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlParameter[] param = new SqlParameter[2];
param[0]= new SqlParameter("@EmpID", SqlDbType.Int);
param[0].Value = txtEmpId.Text;
param[1]= new SqlParameter("@Date", SqlDbType.VarChar,50);
param[1].Value = txtDate.Text;
SqlDataReader reader = DNDatabase.ExecuteStoredProcedureReader("RetrieveDeatails", param);
while (reader.Read())
{
gridConfirm.DataSource = reader;
gridConfirm.Columns[0].Visible = false;
gridConfirm.DataBind();
Session["Task_List"] = reader;
}}
here is stored Procedure code
public static SqlDataReader ExecuteStoredProcedureReader(string procedureName, SqlParameter[] parameters)
{
SqlConnection _conn = new SqlConnection(DNDatabase.SQLConnectionString);
SqlCommand cmd = new SqlCommand(procedureName, _conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procedureName;
cmd.CommandTimeout = 300;
try
{
foreach (SqlParameter param in parameters)
{
cmd.Parameters.Add(param);
}
_conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception sqlExc)
{
throw new Exception("An error occured", sqlExc);
}
finally
{
if (_conn != null)
_conn.Close();
}
}
This looks like a bad idea to me:
You execute that and then call
reader.Read()again, continuing until there’s nothing left to read. Presumably you also close the reader at some point (I’d hope – ideally with ausingstatement). Fundamentally, aSqlDataReaderis a connected resource – it’s like a stream to the database. It’s not something you should be holding onto for longer than you need to, and it’s certainly not something you should be putting in a session, even if you didn’t effectively invalidate it with the subsequentRead()call.I assume that data binding works by fetching the data when you call
DataBind(), but there’s no indication of what you’re trying to achieve by putting a reference to the reader itself into the session.I suggest that:
DataTableor some other “disconnected” form)Additionally, you should consider why you want to loop – currently you’re basically going to loop over all the results and only the last one is going to be displayed (because you’re overwriting the databinding each time). Is that really what you want?