Sunday, August 23, 2009

Alternating background colors for odd and even tablix rows

In this blog post I will describe how you can add alternating background colors to SSRS tablix odd and even rows.
What do you need to know is that expression evaluation rules in RS 2008 have changed as a result of the new on-demand processing model. As a result, state in class-level instance variables is discarded as you page through the report which makes maintaining state trickier between page requests. However, RS 2008 introduces report variables that guarantee one-time evaluation semantics.

How we can reuse it to accomplish our goal:

  • Create a function that will update _evenRow flag state each time it's called.
Open report properties box -> Code tab -> Add next code:

Public _evenRow As Boolean

Public Function EvenRow() As Boolean
 _evenRow = Not _evenRow
return _evenRow
End Function

  • Create a variable within Row group and set the expression to call EvenRow function. Since it will be evaluated one time per each row it's what we need.

  • Set row background color depending on variable state.
=iif(Variables!EvenRow.Value, "LightGrey", "Transparent")

  • and finally the outcome



Regards,
Oleh

3 comments:

Anonymous said...

Simple way.... divide by 2... even numbers return whole numbers and wont contain a decimal "." So use a InStr to find a "."

=iif( InStr((RowNumber(nothing) / 2),"." )>0 , "LightGrey", "Transparent")

Pavel Birioukov said...

More "pure" way ;)
=iif( RowNumber(nothing) Mod 2 = 0, "Transparent", "LightGrey")

MykMyrs said...

Thank you for the information and working example. I changed the code in the Background property to be:

=iif( (RowNumber(nothing)+1) Mod 2 = 0, "Transparent", "LightGrey")

With this change, the odd-numbered rows are transparent and the even-numbered rows are LightGrey.

In the other examples, the first detail row had a background color and I wanted the even-numbered rows to be colored.