在使用ReportViewer時
如果有欄位是用到"除式" (=Fields!P.Value / Fields!C.Value)
並且分母不幸是0時 (Fields!C.Value=0)
會發現此欄位會顯示#Error(中文的話是#錯誤)
以為用IIF判斷就可以避開
=IIf(Fields!C.Value = 0, "N/A", Fields!P.Value / Fields!C.Value)
結果沒有想到一樣還是Error
找了一下微軟的文件看到(中文翻的還沒有這段文字,英文的才有....=.=)
Because the IIf function does not use short-circuit evaluation, it always evaluates all three of its arguments.
The If operator evaluates its first argument and, depending on the value of the first argument, either the second or the third argument.
所以是因為IIF 不論他是否有滿足條件 他都會執行三段引數
所以即使 Fields!C.Value = 0 他還是會執行到 Fields!P.Value / Fields!C.Value
造成有除數為0的錯誤
因此要把除的動作分成兩段
=IIf(Fields!C.Value = 0, "N/A", Fields!P.Value / IIf(Fields!C.Value = 0, 1, Fields!C.Value))
主要是參照這篇
End of Amnesia (Avoiding Divide By Zero Errors) 有遇到這樣問題的人可以看看