This is causing me a headache. I know this question (or atleast variants of it) has been asked many times but before one flags it as a duplicate please consider the following code:
string myConnectionString = myConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ToString();
SqlConnection mySQLConnection;
SqlCommand mySQLCommand;
SqlDataReader mySQLDataReader;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
mySQLCommand = new SqlCommand("SELECT TOP 1 * FROM Table ORDER BY Id DESC", mySQLConnection);
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
using(mySQLDataReader = mySQLCommand.ExecuteReader())
{
if (mySQLDataReader.HasRows)
{
if (mySQLConnection.State == ConnectionState.Open)
{
while (mySQLDataReader.Read())
{
//Perform Logic : If the last record being returned meets some condition then call the below method
MethodCalled();
}
}
}
}
MessageBox.Show("Connection state: " + mySQLConnection.State);
}
I would like to find a way to either:
- Close the reader after it has finished reading
- Break out of the
while-loop
when it has finished reading and there are no more rows left
But I just keep on getting a SqlException
stating the following:
invalid attempt to call read when reader is closed
Just from broad observation, I can trace that error is due to me returning data that contains one row only. The problem is that after it has read that row, the compiler goes back to While(mySQLDataReader.Read()){}
and attempts to read through a table that does not contain any rows.
I attempted the following:
Wrapping the
ExecuteReader()
from the command object in ausing
block so that it automatically closes the reader and the connection respectively once it has done reading like so:using(mySQLDataReader = mySQLCommand.ExecuteReader()) { //Logic performed }
Just before the closing brace of the
while-loop
, I tried checking if there are any more rows left/returned from the sql command and breaking out the loop once that condition is satisfied:if(mySQLDataReader.HasRows == false) //No more rows left to read { break; //break out of loop }
Both attempts were unsuccessful. How can I get around this?