I would like to make a listview (detailed) with many similar items in it. To be more readable I would like it to have every listview.items.count % 2 == 0 row as backolor.lightgray.
I have made a listviewColumnSorter as described in this site:
http://support.microsoft.com/kb/319401
After some modification, so that the data looks “similar” to the one I need to use, my code is following:
public partial class Form1 : Form
{
private ListViewColumnSorter lvwColumnSorter;
public Form1()
{
InitializeComponent();
lvwColumnSorter = new ListViewColumnSorter();
this.listView1.ListViewItemSorter = lvwColumnSorter;
}
private void Form1_Load(object sender, EventArgs e)
{
ColumnHeader columnheader; // Used for creating column headers.
ListViewItem listviewitem; // Used for creating listview items.
// Ensure that the view is set to show details.
listView1.View = View.Details;
for (int i = 0; i < 10; i++)
{
listviewitem = new ListViewItem("item" + i.ToString());
if (listView1.Items.Count % 2 == 0)
{
listviewitem.BackColor = Color.LightGray;
listviewitem.SubItems.Add("xxx");
}
else
listviewitem.SubItems.Add("yyy");
this.listView1.Items.Add(listviewitem);
}
// Create some column headers for the data.
columnheader = new ColumnHeader();
columnheader.Text = "First Name";
this.listView1.Columns.Add(columnheader);
columnheader = new ColumnHeader();
columnheader.Text = "Last Name";
this.listView1.Columns.Add(columnheader);
// Loop through and size each column header to fit the column header text.
foreach (ColumnHeader ch in this.listView1.Columns)
{
ch.Width = -2;
}
}
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.SortColumn)
{
// Reverse the current sort direction for this column.
if (lvwColumnSorter.Order == SortOrder.Ascending)
{
lvwColumnSorter.Order = SortOrder.Descending;
}
else
{
lvwColumnSorter.Order = SortOrder.Ascending;
}
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
this.listView1.Sort();
}
}
(+ the ListViewColumnsSorter class from msdn site.)
If you sort for the second column (Last name), you will see, that all xxx columns are grey and yyy are white, and as colors are seem to be bound to data, my original idea of having every second column grey, is now ruined.
Can I somehow keep the sorting function, and having always every second row grey, independent from the data?
pic:

So to be perfectly clear, after sorting in any column, I would like to keep every second row Lightgrey. How to achieve this?
(.net 4)
This is soooo typical. I googled and tried 2 hours before posting this, and found the answer 10 minutes later…
Alternate Color in ListView C# (.Net 3.5)?
Simply add
to the end of the listview1_columnClick function. where:
Sorry for these extra posts