Question

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

Was it helpful?

Solution

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?

OTHER TIPS

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

try

class ListViewItemComparer : IComparer

not

class ListViewItemComparer : IComparer<ListViewItem>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top