Problem with DBNULL and Integers

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
 
M

Morten Wennevik

Hi Bill,

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

If Row("MonthsPaid") Is DBNull.Value
 
K

Kevin Thomas

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
 

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