views:

302

answers:

2

Hi,

I want to sort a ListView control in C# based on columns. I have created ColumnClickEventHandler:

    private void contactsListView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        contactsListView.ListViewItemSorter = new ListViewItemComparer(e.Column);
        contactsListView.Sort();
    }

Where ListViewItemComparer class looks like this:

   class ListViewItemComparer : IComparer<ListViewItem>
{
    private int col;
    public ListViewItemComparer()
    {
        col = 0;
    }
    public ListViewItemComparer(int column)
    {
        col = column;
    }
    public int Compare(ListViewItem x, ListViewItem y)
    {
        int returnVal = -1;
        returnVal = String.Compare(x.SubItems[col].Text, y.SubItems[col].Text);
        return returnVal;
    }
}

This code won't compile cause contactsListView.ListViewItemSorter is type IComparer and class ListViewItemComparer is IComparer.

Is there a way to explicitly cast one to the other? Or just do sorting another way?

Thanks in advance

A: 

I believe that the comparer class should be IComparer, not IComparer<type>. here is an article that might help, it uses the SortDescriptions.

Muad'Dib
A: 

The generic IComparer<T> and the non-generic IComparer aren't convertible from one another.

Maybe your ListViewItemComparer should implement the non-generic IComparer instead?

Tim Robinson
You are right. I forgot to use System.Collections (I had just System.Collections.Generic). That's why when I saw missing IComparer<> type I've just put it in :PThanks and happy programming :)
kyrisu