Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32501

What is the best way to find out whether image column is null or not?

Problem Definition: I have a table in a SQL Server database. This table has an column of type image and it allows null values. I'm going to read this table using SqlDataReader and show the images if they are available.

What I tried first time: To check whether the image column is null or not I did this

SqlDataReader reader = command.ExecuteReader();  // command is a SqlCommand

while(reader.Read())
{
    if(reader["Image"] != null)     // Image is a column name of the table
    {
        //Do something
    }
}

The result: But it never equals to null (I also checked the Equal method). This column never is null even if has not data inserted (In SQL Server I can see it is actually null)

What I tried second time: So I tried this code and its working but I wonder why it doesn't return null.

SqlDataReader reader = command.ExecuteReader();  // command is a SqlCommand

while(reader.Read())
{
    if(reader["Image"].GetType() != typeof(System.DBNull)) 
    {
        //Do something
    }
}

Question: Any idea to explain this behavior? I will be pleased if there is a better way to find out whether the columns of type Image in SQL Server Tables are null or not.

Upvotes: 1

Views: 3211

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190956

You should just check for DbNull this way.

if(reader["Image"] != DbNull.Value)     // Image is a column name of the table
{
    //Do something
}

Upvotes: 4

Related Questions