Scott Selby
Scott Selby

Reputation: 9580

Conversion from type 'DBNull' to type 'Decimal' is not valid

I'm getting the error in the title "Conversion from type 'DBNull' to type 'Decimal' is not valid." from this line of code

_event.TotalDollars = IIf((dr("TotalDollars") Is DBNull.Value), "$0", CType(dr("TotalDollars"), Decimal).ToString("c"))

_event.TotalDollars is a string

Why is the third part of IIF statement ever getting evaluated? The whole point of this IIF is so that DBNull values are not attempted to be converted into Decimals.

Upvotes: 2

Views: 2927

Answers (2)

Ceres
Ceres

Reputation: 3668

using DatasetExtensions you could also just do this with a nullable decimal type.

_event.TotalDollars = if(dr.Field(of Decimal?)("TotalDollars"),0).ToString("c")

Upvotes: 1

Jon Egerton
Jon Egerton

Reputation: 41579

Two problems:

IIF evaluates both the True and False operations before returning.

Depending on which version of VS you have you could just use If(condition,true,false) instead (which doesn't)

Also, you're probably better to use IsDbNull(condition) to do the test.

Upvotes: 4

Related Questions