Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms - How to alternate the color of rows in a ListView control?

Using C# Winforms (3.5).

Is it possible to set the row colors to automatically alternate in a listview?

Or do I need to manually set the row color each time a new row is added to the listview?

Based on a MSDN article the manual method would look like this:

//alternate row color
if (i % 2 == 0)
{
    lvi.BackColor = Color.LightBlue;
}
else
{
    lvi.BackColor = Color.Beige;
}
like image 236
John M Avatar asked May 19 '10 15:05

John M


2 Answers

Set the ListView OwnerDraw property to true and then implement the DrawItem handler :

    private void listView_DrawItem(object sender, DrawListViewItemEventArgs e)
    {
        e.DrawDefault = true;
        if ((e.ItemIndex%2) == 1)
        {
            e.Item.BackColor = Color.FromArgb(230, 230, 255);
            e.Item.UseItemStyleForSubItems = true;
        }
    }

    private void listView_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
    {
        e.DrawDefault = true;
    }

This example is a simple one, you can improve it.

like image 142
Pierre-Olivier Pignon Avatar answered Oct 03 '22 11:10

Pierre-Olivier Pignon


I'm afraid that is the only way in Winforms. XAML allows this through use of styles though.

like image 32
Andre Avatar answered Oct 03 '22 12:10

Andre