tags:

views:

46

answers:

5

How can I make is so that a ListViews control's background color for items varies from item to item like in WinAmp along with changing the column header colors?

http://i.imgur.com/30pQy.png

If you look closely you can see the first item is a dark gray and the second is black and so on.

+2  A: 

You can set the listviewItem.backColor property, however this has to be done manually for each alternating line. Alternatively you could use a datagridview which has an alternateRowStyle property that would do this automatically - albeit you'll need to databind your rows in a collection of sorts which is a whole other topic.

For the simple case:

        foreach (ListViewItem item in listView1.Items)
        {
            item.BackColor = item.Index % 2 == 0 ? Color.Red : Color.Black;
        }
ach
A: 

I take it that you add rows (subitems) in a loop? If so use a loop counter to figure out which colour you want.

string[] strings = new string[]{"dild", "dingo"};
int i = 0;
foreach (var item in strings)
{
    Color color = i++ % 2 == 0 ? Color.LightBlue :  Color.LightCyan;
    ListViewItem lv = listView1.Items.Add(item);
    lv.SubItems[0].BackColor = color;
}
Paw Baltzersen
A: 
for (int index = 0; index <= ListView1.Items.Count; index++) 
{
    if (index % 2 == 0) 
    {
        ListView1.Items(index).BackColor = Color.LightGray;
    }

}
Ranhiru Cooray
In your code, first all items will be painted in single color, after that - 1/2 of them will be repainted. That's not very efficient, I guess. So it's better to paint them on add, i.e. only one time.
abatishchev
Yes! I agree... Its just that I cannot find an event for Item Add in the ListView... Item Paint and Sub Item Paint events does not seem to fire....
Ranhiru Cooray
A: 
private static void RepaintListView(ListView lw)
{
    var colored = false;
    foreach (ListViewItem item in lw.Items)
    {
        item.BackColor = colored ? Color.LightBlue : Color.White;
        colored = !colored;
    }
}

You can call this method after item addition. Or use it directly on add

abatishchev
A: 

Handle the DrawItem event on the listbox and set the DrawMode to OwnerDrawVariable. The DrawItemEventArgs provides a BackColor property that can be set based on the index (also in the arg).

Kell