Reputation: 16839
How can I make it 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?
If you look closely you can see the first item is a dark gray and the second is black and so on.
Upvotes: 8
Views: 33719
Reputation: 7451
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;
}
Upvotes: 13
Reputation: 3327
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).
Upvotes: 2
Reputation: 19872
for (int index = 0; index <= ListView1.Items.Count; index++)
{
if (index % 2 == 0)
{
ListView1.Items(index).BackColor = Color.LightGray;
}
}
Upvotes: 0
Reputation: 100358
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
Upvotes: 0
Reputation: 2752
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;
}
Upvotes: 0