Testing for null

T

tshad

I have a query that is returning a null and I am testing for null. The
value being sent back is a varChar(11) from Sql Server. If I do the query
from Query Analyser I get NULL returned.

But if I run the following:
************************************************************
dbReader = myDbObject.RunProcedure("GetNewHire", parameters);
if (dbReader.Read())
{
if (dbReader["SSN"] == null)
ssn = "SSN is equal null";
else
ssn = "SSN is not equal null";
if(dbReader["FirstName"] != null)firstName = (string)dbReader["FirstName"];
if(dbReader["LastName"] != null)lastName = (string)dbReader["LastName"];
if(dbReader["MiddleInitial"] != null)middleInitial =
(string)dbReader["MiddleInitial"];

// if(dbReader["SSN"] != null)ssn = (string)dbReader["SSN"];

************************************************************

If I run this I get "SSN is not equal null". If I uncomment the last line,
I get an error:

System.InvalidCastException: Specified cast is not valid.
at MyFunctions.NewHire.GetNewHire(String& returnString)
at MyFunctions.NewHire.AddNewHire()
at TestDll.Class1.Main(String[] args) in
c:\vsprojects\testdll\class1.cs:line
24

Am I not doing the test correctly? I also tried using (dbReader["SSN"] !=
null), but got the same results.

Thanks,

Tom
 
S

Steven Nagy

You might actually be after DBNull instead?
Try assigning the content of the reader to an "object" and put a watch
on it to see what it is.
But I think DBNull might be what you are looking for.
Null would indicate that dbReader["SSN"] doesn't actually exist in the
reader's collection.
The problem is that it DOES exist, but the value is DBNull.

Hope this helps.
 

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