views:

62

answers:

2

I'm gonna set an alternate color to my ListView rows.
I saw this link but I'm using .Net Framework 3.5 SP1 , so I can't use it.

I've used the following code , but it has problem with ListView Sorting

ListViewItem newListViewItem = new ListViewItem(
    new string[] { item.name.ToString(), 
                   item.code.ToString() });
newListViewItem.BackColor = new Color(240,240,240);
newListViewItem.UseItemStyleForSubItems = true;
newListViewItem.Font = new Font("Tahoma", 9);
listView1.Items.Add(newListViewItem);

Could you please guide me how I can do it?

+1  A: 

It is quite unclear from your snippet, but I'll guess you want alternating colors. Even numbered items colored one way, odd numbered colored another way. Yes, very effective as a reading guide when you have a large number of columns in the view.

And yes, that's going to get mucked up when you sort the items. Right after sorting, you'll need a simple for loop that changes the BackColor property.

    private static void recolorListItems(ListView lv) {
        for (int ix = 0; ix < lv.Items.Count; ++ix) {
            var item = lv.Items[ix];
            item.BackColor = (ix % 2 == 0) ? Color.Beige : Color.White;
        }
    }

Call this after sorting. Or after filling the ListView. I suck at colors, please pick your own.

Hans Passant
+1  A: 

Here is a easy way to do it -> Alternate background

anivas
The link is for WPF, I wanna it in WinForms.
Mohammad