Results 1 to 3 of 3

Thread: FormatCurrency function in Iif shouldn't even be invoked

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    May 2004
    Location
    South Charleston, WV, USA
    Posts
    607

    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.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    May 2004
    Location
    South Charleston, WV, USA
    Posts
    607

    Re: FormatCurrency function in Iif shouldn't even be invoked

    Thank you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width