質問

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.

役に立ちましたか?

解決

You should just check for DbNull this way.

if(reader["Image"] != DbNull.Value)     // Image is a column name of the table
{
    //Do something
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top