Sometimes I find myself applying the same formatting or performing the same task to many elements within a SQL Server Reporting Services (SSRS) report.
When this happens, I consider writing a reusable function to perform this task or formatting. Functions can be added directly to an SSRS report.
To add code to an SSRS report, open the report and select Report | Report Properties from the menu. The Report Properties dialog displays. Select the Code tab to bring this tab forward (Fig. 1).
Fig 1: The Code tab of the SSRS Report Properties dialogue
Note: If, like me, you are having trouble writing valid code with the IntelliSense or other syntax-checking, It might be helpful to create a console application in Visual Studio and type the same function in order to validate the function's syntax and functionality.
In SSRS, you assign an expression to an object’s property using the Expression Editor (Fig. 2)
Fig2: The SSRS Expression Editor
In an Expression editor of any object on the report, you can call the function with the word "Code", followed by ".", followed by the name of the function.
For example, I found that I had a number of textboxes that displayed numeric data. I wanted every number to display with the following rules:
- Format the numeric output so exactly 2 digits appear to the right of the decimal point
- Print "N/A" for null values.
I could accomplish this by doing the following:
- Set the formatting of every textbox to "##,##0.00;(##,##0.00)"
- Change the expression in each textbox to something like:
=Iif(IsNothing (Fields!Price), "N/A", Fields!Price)
But this is inefficient because one needs to perform the above steps for every textbox where this change is needed.
Instead, I created the following function and embedded it into the report:
Public Shared Function FormatAs2Digits(ByVal input as Nullable( of decimal)) as string return Iif(IsNothing (input), "N/A", Format(input, "##,##0.00;(##,##0.00)")) End Function
Then, I could set the expression of each textbox to something similar to the following
Be aware that your report runs under a specific user context and that user will likely have very limited access rights, so your functions will be limited in what that user context can do. Generally, I only use functions to format data and perform other tasks encapsulated within the report.
Despite its limitations, an embedded function is an excellent way to create reusable code and consume it in multiple objects within an SSRS report.