How to determine if a DB column value is null?

R

Raymond Du

Hi,

I used a SqlDataReader to get data from SQL server, say the variable name is
drEmployee.

I tried to determine if HireDate column in drEmployee is null by using C#
code:
if (drEmployee["HireDate"] != null)

Doesn't work at all, I also setup breakpoint, added drEmployee["HireDate"]
to QuickWatch window, it showed:
{System.DBNull}

(drEmployee["HireDate"] != null) just simply returns true.

Any Idea?

Thanks in Advance
 
G

Guest

null according to databases is different as far as null from OO point of view
hence, try checking null value in your column with

if (drEmployee["HireDate"] != DBNull.value)

HTH
Kalpesh
 
M

Mary Chipman

So what action do you want to take if it's null? Depending on what you
want to do, it's sometimes more efficient to put the null test in
either the SELECT (if you want it to run line by line) or the WHERE
clause (if you don't want to fetch the nulls).

--Mary
 
M

Miha Markic [MVP C#]

Hi Raymond,

Try drEmployee.IsDBNull method that takes an index of column (GetOrdinal
method).
 
M

Miha Markic [MVP C#]

Hi,

I think that IsDBNull is more correct as it does more checks, such as
checking for null.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top