0

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.

1 Answer 1

5

You need to call the Read method before trying to access any columns:

while (dr.Read())
{
    if (!dr.IsDBNull(0))
        maxID = dr.GetInt32(0);
}

But... if you only need a single value then you should probably use something like ExecuteScalar rather than a datareader.

Sign up to request clarification or add additional context in comments.

1 Comment

This works, but i'm a little confused as to why it worked with me, but then i didn't work at my coworkers computer with practically the same code. Anyway, thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.