Menu

Zebra-Striping your Windows Forms ListView

August 3, 2013 - .NET, C#

“Zebra-Striping” is the name for a common technique for reports or long lists of items where each row is given a colour distinct from those adjacent to it. The most common is for rows to alternate gray and white backgrounds. The Windows Forms ListView Control does not come with this ability built in, so you have to add it yourself. The problem is that the brute-force approach of setting the background and foreground (if desired) of every item in the control is fraught with peril, because future changes to the ListView such as sorting it will result infunky colourations, Or at the very least you will need to perform the same logic again to colour everything correctly.

One way around this is to exploit the ListView’s OwnerDraw functionality. This can allow you to change the background and foreground of an item based on it’s positional index, but the change will only be made when necessary. Then you can set it to draw the default method and forget about it all.

 

This is the basis for the ZebraStriper class.

The given class allows you to zebra stripe your ListView instances. Here are some examples and what they look like. lvwSortTest is the ListView Control, and zs is a “ZebraStriper” member variable:

This looks like this:

ListView Zebra Stripes: Example 1

ListView Zebra Stripes: Example 1

But how do we customize it? What if we want it to switch between Red,green, and yellow, for that christmasy theme we all love? We got you covered, though we won’t be held liable for your garish design choices:

Which gives us:

Zebra Striped listView Example 2

Zebra Striped listView Example 2

Of course in general it’s a good idea to choose colours that are not so high-contrast. a light gray with a white; a dark gray with black, etc. as well as making sure the text is readable (here, the white text sometimes appears on a yellow background due to the way the sequences line up, which is of course hard to read).

Either way, this particular method works a lot better than simply looking through the control; it only fires for controls that need to be drawn, so it doesn’t actually loop through every item. It also segregates the logic into a separate, reusable class, which can be helpful.

Have something to say about this post? Comment!