Subscribe to Blog.Parse(typeof(PsychoCoder), Richard McCutchen);        RSS Feed
-----

Alternating row colors in ListView

Icon 3 Comments
Recently I was looking for a solution to this quandary for an application I was working on. Based on this AdamSpeight2008 came up with a VB.NET solution to the issue and posted it on his blog, so I thought I'd show the C# solution I came up with.

I do believe in some aspects Adam's solution may be more efficient, as it uses a built-in event for the ListView Control, but I thought it an interesting enough quandary to come up with my own solution, so here it is

/// <summary>
/// method for adding alternating row colows in a ListView control
/// </summary>
/// <param name="lst">ListView we're working with</param>
/// <param name="color1">furst color to use</param>
/// <param name="color2">second color to use</param>
public void SetAlternatingRowColors(ListView lst, Color color1, Color color2)
{
	//loop through each ListViewItem in the ListView control
	foreach (ListViewItem item in lst.Items)
	{
		if ((item.Index % 2) == 0)
			item.BackColor = color1;
		else
			item.BackColor = color2;
	}
}



Happy coding, and can you come up with your own solution?

3 Comments On This Entry

Page 1 of 1

girasquid Icon

11 January 2010 - 02:31 PM
Doesn't C# have a ternary operator? I'd probably use a ternary for something this small, like so:
item.BackColor = item.Index % 2 == 0 ? color1 : color2;


..more of a style quibble than anything, though.
0

PsychoCoder Icon

11 January 2010 - 05:36 PM
Ahh thanks girasquid! I never even thought of that
0

PsychoCoder Icon

12 January 2010 - 10:13 AM
Well I took Adam's idea and implemented this using the ListView's DrawItem event like so

private void ListViewPrograms_DrawItem(object sender, DrawListViewItemEventArgs e)
{
	e.DrawDefault = true;
	
	e.Item.BackColor = e.ItemIndex % 2 == 0 ? Color.FromArgb(234, 244, 255) : Color.FromArgb(202, 224, 255);;
}



The rows have alternating colors the way I want, but the column headers are gone?
0
Page 1 of 1

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

May 2013

S M T W T F S
      1234
567891011
12131415161718
1920 21 22232425
262728293031 

Recent Entries

Search My Blog

1 user(s) viewing

1 Guests
0 member(s)
0 anonymous member(s)