Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
1  
+1 for ExecuteScalar – Steve Czetty Feb 16 '12 at 17:19
+1 for suggesting ExecuteScalar() – egrunin Feb 16 '12 at 17:19
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. – DFord Feb 16 '12 at 19:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.