tags:

views:

653

answers:

4

I've got this query:

SELECT PICTURE FROM LOGO WHERE LOGONO = ?

("PICTURE" is an Image column in SQL Server)

And this code to read the data:

using (DbDataReader reader = command.ExecuteReader())
{
    if (reader.HasRows)
    {
        if (!reader.IsDBNull(0))
        {
            byte[] buffer = new byte[8000];
            while (reader.GetBytes(0, 0, buffer, 0, 8000) > 0)
                picture.AddRange(buffer);
        }
     }
}

The problem is an InvalidOperationException ("No data exists for the row/column") always gets thrown on the reader.IsDBNull(0) statement when the column contains null.

MSDN says:

Call this method to see if there are null column values before calling the typed get methods (for example, GetByte, GetChar, and so on) to avoid raising an error.

How can I check that the column doesn't contain null without triggering the Exception? Am I going about this in the wrong way?

A: 

I always use the following check and it seems to have always worked for me

if (reader[0] != null && reader[0] != DBNull.Value) { }

Cody C
Tried it. No luck, unfortunately.
ilitirit
+5  A: 

You need to call reader.Read() before accessing any data. From the MSDN docs for Read:

The default position of the DataTableReader is before the first record. Therefore, you must call Read to start accessing any data.

adrianbanks
DOH! Coffee time.
ilitirit
+1  A: 

You did not call reader.Read(). Since your working with a reader, you either need to check if Read returns true for a single record, or use a while loop to iterate through all the records.

if (reader.Read())
{
  // handle single record
}

// or

while (reader.Read())
{
  // handle each record
}
jrista
+1 for clear example
RedFilter
A: 

I apologize... I was assuming the question was "How to check for NULL" not "Why doesn't this code work". Adrian is correct. You need to add a reader.Read() somewhere. I usually use while (reader.Read()) but there are other approaches.

Cody C