p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   VB.NET 2002/2003 Basics (http://p2p.wrox.com/forumdisplay.php?f=76)
-   -   Dealing with DBNull (http://p2p.wrox.com/showthread.php?t=8196)

jaucourt January 15th, 2004 08:49 AM

Dealing with DBNull
 
I'm currently building an object that receives values from a datareader - therefore my code looks a bit like this

Do while dr.Read
   With myobj
      .Prop1 = dr("Field1")
   End With
Loop

Now this obviously raises errors when we get null values, so I changed my code to the following;

Do while dr.Read
   With myobj
      .Prop1 = IIF(IsDBNull(dr("Field1")), "", dr("Field1"))
   End With
Loop

Whilst this works, it's not very elegant. I can create my own function where you passed in a value and it returns either the value or a zero length string. However, I wondered if there was a native vb.net command that would do something similar.


planoie January 15th, 2004 11:00 AM

I haven't found such a beast. One thing you can consider if you are using a SQL DB (not sure about Access): if you know what columns you might get db nulls on you can write the query to handle this. Instead of just selected the column value, use the COALESCE() function to get the first non-null value.

SELECT COALESCE(myColumn, '') ...

Peter
------------------------------------------------------
Work smarter, not harder.

jlick January 15th, 2004 02:46 PM

Similar to the last post, in MS-SQL server you can use the ISNULL() funciton.

Lets say the nullable field is Price, and you want null values to be 0. You could use something like the following:

Code:

SELECT ISNULL(Price, 0) 'Price', ...
FROM ...
WHERE ...

This would return a field named Price. If the column value is not null, then it will return the value of the Price column. If the column value is null, then it would return 0.

You need the 'Price' to have it named, otherwise it would not keep the Price name.

John R Lick
JohnRLick@hotmail.com

jaucourt January 16th, 2004 10:59 AM

Thanks for the advice



All times are GMT -4. The time now is 08:25 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.