Friday, 18 November 2011

Conditional Formatting Using RDLC

I recently came across a problem on a report we needed to run that returned either a date or some text. The return value of the data then needed to be colour coded in a traffic light style so that dates in the past were red, dates in the future were Green and dates within the next month were orange. Additionally if the value was set to N/A then the field was to be turned gray.

Looking at the problem it seemed straight forward and I headed straight to the expression field of the color parameter for the column. I entered a switch statement that cast the value to the appropriate type (Date or string) and then attempted to do the logic. This turned into a large dead end as the casting of one type then seemed to not allow any further casts! After a few searches I couldn't find the answer so posted on the MSDN forums. After about 6 months of no answer I had pulled the last of my hair out and had put in a compromised solution.

The problem still nagged at me until I came across using code and shared assemblies in RDLC. To solve the problem I simply put a function into the code block and set the color parameter of the field to the expression. At last, a fix (although really its a workaround as it should have worked in the expression). Here is the function I put in:

 Public Function ColorFormat(ByVal cellValue As Object) As String
  
     Dim cellDate As Date
     Dim cellString As String
  
     cellString = CStr(cellValue)
  
     If Date.TryParse(cellString, cellDate) Then
       If (cellDate < Date.Now.AddMonths(1)) Then
         If (cellDate < Date.Now) Then
           Return "Red"
         Else
           Return "Orange"
         End If
       End If
     Else
       If String.Compare(cellString, "EXPIRED", True) = 0 Then
         Return "Red"
       End If
     End If
  
     Return "Black"
  
   End Function  

The functions in the code block need to be in VB and debugging whilst running is impossible so putting into a shared assembly is the preferred option.

No comments:

Post a Comment