tags:

views:

500

answers:

2

I have some formulas in my reports, and to prevent divsion by zero I do like this in the expression field:

=IIF(Fields!F1.Value <> 0, Fields!F2.Value/Fields!F1.Value, 0)

This normally works fine, but when both F1 and F2 are zero, I get "#Error" in the report, and I get this warning: "The Value expression for the textbox ‘textbox196’ contains an error: Attempted to divide by zero."

Why is that?

+2  A: 

IIF() is just a function, and like with any function all the arguments are evaluated before the function is called, including Fields!F2.Value/Fields!F1.Value. In other words, it will attempt to divide by zero in spite of the Fields!F1.Value <> 0 condition.

Joel Coehoorn
Ah, yes, of course, starting to remember VB.. But, what kind of solutions exits to this problem?As far as I know, I cannot enter an VBA snippet as an expression, or am I wrong?
neslekkiM
I'm not sure: VB9 (.Net 3.5) supports a new If() _operator_ that works like a C-based ternary operator (?). VB8 (.Net2.0) supports inline If/Else constructs. But I don't think either will work with ReportViewer.
Joel Coehoorn
I might be wrong, but I don't think this explains the problem. neslekkiM's thing works fine when only F1 == 0, but not when *both* are 0, right? Plus Joel, your division expression doesn't match what neslekkiM wrote - his has F1 as the divisor, not F2.
cori
Fixed the F1/F2 typo.
Joel Coehoorn
And what's more...If you add an column to an dataset, uses an expression with IIF(F1<>0,F2/F1,0) THEN the damn thing WORKS??Why is IIF implemented so differently all over the place?Exce, VB, ReportingServices, ADO, etc.. sigh..
neslekkiM
+1  A: 

There has to be a prettier way than this, but this should work:

=IIF(Fields!F1.Value <> 0, Fields!F2.Value / 
   IIF(Fields!F1.Value <> 0, Fields!F1.Value, 42), 0)
Bjorn Reppen
Disgusting, but works..Why can't I simply write:IF Fields!F1.Value <>0 Then Fields!F2.Value / Fields!F1.ValueElse 0 End Iflike CrystalReports.. which I'm migrating away from.. sigh.
neslekkiM

related questions