Difference betweene DBNull and Null(when dealing with ADO.NET)

To compare the values against the db values, generally we use NULL to filter out the null values in the db; which is as shown below:


       SqlDataReader dr=  sqlCommand.ExecuteReader();
   
        While(dr.read())
        {
           if(dr[index] != null)         // Index depends on the no:of values in the table/the column mentioned in the sqlcommand text..
                    // Some operation x
          else
                    // Some operation y
        }

But the thing here is, null in C#/VB is used to check against the reference of the object. But whenever we compare a db value against the null, then the condition becomes true obviously as that is a db value and not the object. Hence, in such sort of conditions we can make use of DBNull.Value property, which could sort out our problem; as shown below:


   SqlDataReader dr=  sqlCommand.ExecuteReader();
   
        While(dr.read())
        {
           if(dr[index] != DBNull.Value)
                    // Some operation x
          else
                    // Some operation y
        }

So, make use of DBNull.Value when dealing with ADO.NET.. :)

~Happy coding.. :)

No comments:

Post a Comment