FormatCurrency function in Iif shouldn't even be invoked
I have code that works:
Code:
If IsDBNull(dbReader("cost")) Then
Me.CostTextBox.Text = String.Empty
Else
Me.CostTextBox.Text = FormatCurrency(dbReader("cost"), 2)
End If
And the following which does not work:
Code:
Me.CostTextBox.Text = IIf(IsDBNull(dbReader("cost")), String.Empty, FormatCurrency(dbReader("cost"), 2))
It returns the error "Conversion from type DBNULL to type Currency is not valid" when dbReader("cost") is null. If dbReader("cost") is null it should put String.Empty in Me.CostTextBox, just like the first code. It shouldn't be hitting the currency function at all.
I can always use the first method but I'd like to know why the Iif doesn't work.
Using VB.Net Express 2010.
Re: FormatCurrency function in Iif shouldn't even be invoked
The reason is that IIf is a function, not an operator. As such, if you use expressions as arguments then those expressions MUST be evaluated and it's the values returned that actually get passed to the function parameters.
The good news is that Microsoft did add an operator to VB in 2008 that does what you are wanting IIf to do there. Just change 'IIf' to 'If' and it will work as you intend.
Re: FormatCurrency function in Iif shouldn't even be invoked