DBNull warnings when performing stored procedure
One column in my database (of type double) has some null values. I am executing a sored procedure to get the data in my app
wipDBTableAdapters.XLSFacturiTableAdapter TAFacturi = new wipDBTableAdapters.XLSFacturiTableAdapter();
var dtfacturi = TAFacturi.GetData(CodProiect);
Then i try to do something like this:
if (dtfacturi[i].CANTITATE == null)
{
//do something
}
this is giving a warning :
The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?
However when i run my code i ge开发者_运维技巧t the following exception:
StrongTypingException
The value for column 'CANTITATE' in table 'XLSFacturi' is DBNull.
How am I supposed to resolve this ?
While working with data in DB and need to check NULL values use DBNull class instead of .NET null.
Database NULLs are different from null
, you should use IsDBNull
to check for database NULLs.
Edit: Mixed up VB.Net with C#
Compare with DBNull.Value
rather than the VB specific IsDBNull
.
Try this:
if (dtfacturi[i].CANTITATE == DBNull.Value)
{
//do something
}
A value of type 'double' is indeed never null; if you want to export into an array of doubles, you need to have two columns in the database, one containing the data and one containing a flag as to whether the data is valid or not.
This is really a bug in your database-to-array adapter code; I can't find any google hits for XLSFacturiTableAdapter so I'm not sure who to shout at.
DBNull
is not null
Check DBNull documentation on MSDN
Try this test :
if (DBNull.Value.Equals(dtfacturi[i].CANTITATE))
{
//do something
}
When using TypedDataSets, check if coloumn is null this way..
if (dtfacturi[i].IsCANTITATENull())
{
//do something
}
Also note that, C# null is different than Database null. Type of your coloumn is double which is a value type that can never be null. In order to check if your coloumn value is null you need to compare it with DBNull.Value.
精彩评论