471,354 Members | 2,101 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,354 software developers and data experts.

Problem with DBNULL and Integers

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

Jul 21 '05 #1
2 2904
Hi Bill,

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

If Row("MonthsPaid") Is DBNull.Value
On Fri, 06 May 2005 17:50:05 +0200, BillG <Bi***@discussions.microsoft.com> wrote:
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


--
Happy coding!
Morten Wennevik [C# MVP]
Jul 21 '05 #2
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

"BillG" <Bi***@discussions.microsoft.com> wrote in message
news:10**********************************@microsof t.com...
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

Jul 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Miky | last post: by
6 posts views Thread by Ron L | last post: by
5 posts views Thread by Chad | last post: by
30 posts views Thread by dbuchanan | last post: by
17 posts views Thread by John | last post: by
2 posts views Thread by BillG | last post: by
6 posts views Thread by tshad | last post: by
7 posts views Thread by David | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.