Null Database Values

  • Thread starter Thread starter Dan Keeley
  • Start date Start date
D

Dan Keeley

Hi,

This is probably not a dotnet specific issue, however i'm using dotnet so
here goes,.

I'm setting a text value of a field like so:

txtFax.Text = currentRow("FaxNumber")

However depending on the row, this value may be null.

This throws an exception because "Cast from type DBNULL to type String is
not valid"

Whats the proper way to deal with this?

Do i really have check the returned value for every field and substitute ""
where necessary?

Thanks,
Dan
 
Dan
I check to see if the value is null before assiging. In my case with the
Reader object

If Not(rdr.IsDBNull(1)) Then myvar = rdr.GetString(1)
 
Dan Keeley said:
This is probably not a dotnet specific issue, however i'm using
dotnet so here goes,.

I'm setting a text value of a field like so:

txtFax.Text = currentRow("FaxNumber")

However depending on the row, this value may be null.

This throws an exception because "Cast from type DBNULL to type
String is not valid"

Whats the proper way to deal with this?

Do i really have check the returned value for every field and
substitute "" where necessary?


You could write a function to do it:

Function MyFunction(ByVal o As Object) As String
If o Is DBNull.Value Then
Return ""
Else
Return o.ToString
End If
End Function


As you want to substitue Null by a zero-length string, how do you
distinguish between Null and a zero-length string when you look at the
filled textbox?
 
You need to check for null first before assigning:

if not currentRow("FaxNumber") = DBNull.Value

end if
 
Compare the value to System.DBNull.Value:

If Not (your reference to the possible null) Is DBNull.Value Then
.....
'Assign

Else
....
'Handle the null case for example:
myVal = String.Empty
End if
 
I ran into this problem early on, so I ended up just adding a Check/Select
function pair for each data type. I know it's not the most efficient coding
method, but it works. Each Select function selects the value into an object
and returns the value of the Check function, which converts the object to
its specific data type, or returns 0 for numerics and "" for strings. Then
just put all of those functions in a global Query class or something along
those lines, and you can always access them easily.

Mike


Michael Caputo
Programmer/Database Administrator
Simon Economic Systems Ltd.
 
Back
Top