Problem with DBNULL and Integers

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

This is my code. If the value coming in from the database table is null, I
wish to place a 0 in the column or otherwise the value itself. Everything I
try this code I get an error. Am I doing this wrong that a null value cannot
be converted to any other type?

If Not Row("MonthsPaid") Is DBNull.Value Then
paid.MonthsPaid = 0
Else
paid.MonthsPaid = Convert.ToInt32(Row("MonthsPaid"))
End If
 
Hi Bill,

VB isn't my strong side, but shouldn't your condition be swapped?

If Row("MonthsPaid") Is DBNull.Value
 
Well here's one way to do it. Add this function to your class:

Public Function NullToZero(ByVal oValue As Object) As Double
If IsNothing(oValue) OrElse Convert.IsDBNull(oValue) OrElse Not
IsNumeric(oValue) Then
NullToZero = 0
Else
NullToZero = Convert.ToDouble(oValue)
End If
End Function

Now you can reduce your code-snippet below to just one line:

paid.MonthsPaid = NullToZero(Row("MonthsPaid"))


Kevin
 
Back
Top