Change item list

How can I make it so that ListViews control the background color for elements, varying from element to element, for example, in WinAmp, as well as changing the colors of column headers?

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

If you look carefully, you will see that the first element is dark gray, and the second is black, etc.

+5
source share
5 answers

You can set the property ListViewItem.BackColor, however, this must be done manually for each alternating line. Alternatively, you can use DataGridViewone that has a property AlternateRowStylethat will do this automatically - although you need to bind data to your rows in a collection, which is a whole different topic.

For a simple case:

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

DrawItem DrawMode OwnerDrawVariable. DrawItemEventArgs BackColor, ( arg).

+1

I suppose you add lines (subitems) in a loop? If so, use a loop counter to find out what color 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;
}
0
source
for (int index = 0; index <= ListView1.Items.Count; index++) 
{
    if (index % 2 == 0) 
    {
        ListView1.Items(index).BackColor = Color.LightGray;
    }

}
0
source
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 adding an item. Or use it directly when adding

0
source

All Articles