none
Expression property oddity RRS feed

  • Question

  • I was given a bug to fix that was a divide by zero exception, easy enough to find.  Here's the original code:
            Dim dt As DataTable = DABase.GetData(cmd)
            dt.Columns.Add("DeficitPercent", Type.GetType("System.Single"))
            dt.Columns("DeficitPercent").Expression = "(Expenditures - Revenues) / Expenditures * 100"

    So, I replaced the last line with this:
            dt.Columns("DeficitPercent").Expression = "IIF(Expenditures = 0, 0, (Expenditures - Revenues) / Expenditures * 100)"

    To my surprise it still threw an exception!!!  So I was playing around a bit and decided to break up the expression into mutliple columns, and this worked:

            dt.Columns.Add("Diff", Type.GetType("System.Single"))
            dt.Columns("Diff").Expression = "Expenditures - Revenues"
            dt.Columns("DeficitPercent").Expression = "IIF(Expenditures = 0, 0, Diff / Expenditures * 100)"

    Can anyone explain why the latter works and the former doesn't?
    Thursday, March 20, 2008 5:35 PM

All replies

  • That's very strange.  What are the types of the Expenditures and Revenues columns?

     

    (Unrelated tip:  you can also use dt.Columns.Add("DeficitPercent", typeof(System.Single)), which a) is a bit less to type and b) checks your typos at compile-time instead of run-time.)

     

    Monday, March 24, 2008 7:09 PM
  •  Robert Rossney wrote:

    That's very strange.  What are the types of the Expenditures and Revenues columns?


    They are coming from Oracle and the columns are of type Number.  The actual columns in the resulting DataTable are System.Decimal.

     Robert Rossney wrote:

    (Unrelated tip:  you can also use dt.Columns.Add("DeficitPercent", typeof(System.Single)), which a) is a bit less to type and b) checks your typos at compile-time instead of run-time.)


    Good tip.  Most of that was existing code, so I was just copy/pasting.  Now that I look though, that's the only place in the entire application that uses that syntax!  Funny.
    Thursday, March 27, 2008 5:20 PM