Listview Sorting (2 'fields')  
Author Message
Ayukawa





PostPosted: Visual C# Express Edition, Listview Sorting (2 'fields') Top

I have a listview with a single column that I'm using to display items that have an image specified in their .ImageIndex property. What I'd like to do is sort by both the image index, and the text of the entry, so that items with the same image are together and sorted alphabetically.

I was trying to add a customized sorter:

class ListViewItemComparer : IComparer
{
public ListViewItemComparer()
{
}
public int Compare(object x, object y)
{
return string.Compare(((ListViewItem)x).ImageIndex, ((ListViewItem)y).ImageIndex);
}
}

but all I get when I try to compile is an error:

Using the generic type 'System.Collections.Generic.IComparer<T>' requires '1' type arguments


I'm also unsure as to how to sort the items alphabetically in addition to by the imageindex.




Visual Studio Express Editions38  
 
 
nobugz





PostPosted: Visual C# Express Edition, Listview Sorting (2 'fields') Top

You're picking up the generic version of IComparer. Look at the top of your form's code and change
using System.Collections.Generic;
to
using System.Collections;

Here's a sample implementation that first checks on the ImageIndex, then a case-insensitive comparison on the item's text:

public int Compare(object x, object y)
{
ListViewItem item1 = (ListViewItem)x;
ListViewItem item2 = (ListViewItem)y;
if (item1.ImageIndex < item2.ImageIndex) return -1;
if (item1.ImageIndex > item2.ImageIndex) return 1;
return string.Compare(item1.Text, item2.Text, true);
}