One of the guys working on a project with me keeps getting an error when the code trys to validate if SqlDataReader returns a null value in a column. He runs this code:
if (!DB_Conn.isConnected()) DB_Conn.Connect();
using (SqlDataReader dr = DB_Conn.QueryDB(query))
{
if (dr.HasRows && !dr.IsDBNull(0))
{
maxID = dr.GetInt32(0);
}
}
But gets an error that Its an invalid attemtp to read when no data is present at the !dr.IsDBNull(0) command.
If i run this same code but i query a different table, it works.
Also, i run both queries and they return the expected null value. The querys are:
SELECT MAX(ID) FROM Loan;
SELECT MAX(ID) FROM InternationalSwap;
I dont think the querys have any affect on the reason why we are getting this error at one machine and not the other.
You need to call the
Readmethod before trying to access any columns:But… if you only need a single value then you should probably use something like
ExecuteScalarrather than a datareader.