views:

878

answers:

2

I have an RDLC report that I am rendering directly to the Response Stream as PDF (rather than using the ReportViewer). In the code that renders the report, it's DataSource is bound to a List(Of ClassA) objects defined in a custom assembly. This seems to work for the most part. My problem is that I can't seem to handle the situation where a nested object is null. For example, given ClassA and ClassB (the nested object) defined as follows:

    Public Class ClassA
       Public Id As Integer
       Public Name As String
       Public TheNestedObject As ClassB
    End Class

    Public Class ClassB
       Public Id As Integer
       Public Name As String
       Public TheParentObject As ClassA
    End Class

Whenever I try to conditionally display an "N/A" if Class B is null in my expression as follows:

=IIf(IsNothing(Fields!TheNestedObject.Value,"n/a", Fields!TheNestedObject.Value.Name))

the report displays "#Error" if TheNestedObject is null. If TheNestedObject is not null, it correctly displays the Name.

What am I doing wrong here?

Thanks!!!

A: 

I don't know for sure how to fix your problem, but I have a couple of suggestions...

(1) Perhaps if you changed your IIF statement to be:

IIf(IsNothing(Fields!TheNestedObject,"n/a", Fields!TheNestedObject.Value.Name))

IIf always evaluates all of the arguments, so it is trying to evaluate TheNestedObject.Value. If TheNestedObject is NULL or NOTHING, then I wouldn't be surprised to see it throw an error.

(2) Another idea would be to modify your constructor to add an "empty" "B" object whenever there is no "B." For example, A.TheNestedObject would point to a "B" object which has no data. B.Id would be 0 (by default) unless you made it a nullable Int. B.Name would be "". Etc.

Scott
A: 

The iif function evaluates all arguments and thus Fields!TheNestedObject.Value.Name gets evaluated and gives the error since Fields!TheNestedObject.Value is null.

I ended up adding some custom code to the report. It's under report properties -> Code tab.

Public Function GetName(ByRef obj As Object) As String
    If obj Is Nothing Then
        Return "n/a"
    Else : Return obj.Name
    End If
End Function

And then your textbox expression is:

=Code.GetName(Fields!TheNestedObject.Value)

The function returns "n/a" when it's null and the Name property when it's not.

Ezweb