Sorting ListView columns in .NET 2.0

G

Gustaf

I'm porting code from VS 2003 to VS 2005, and can't get column sorting
to work as before. This is code I found somewhere and used without
acctually understanding it. I still don't fully understand it, which
makes it hard to see what's wrong now. In VS 2003, it allowed me to
click on a ListView column to get the list contents sorted on that column.

private void listView1_ColumnClick(object sender,
ColumnClickEventArgs e)
{
this.listView1.ListViewItemSorter =
new ListViewItemComparer(e.Column);
}

class ListViewItemComparer : IComparer<object>
{
private int col;

public ListViewItemComparer()
{
col = 0;
}

public ListViewItemComparer(int col)
{
this.col = col;
}

public int Compare(object x, object y)
{
return String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
}
}

What happens now is that I get an error here:

this.listView1.ListViewItemSorter =
new ListViewItemComparer(e.Column);

that says:

Cannot implicitly convert type 'MyNamespace.ListViewItemComparer' to
'System.Collections.IComparer'. An explicit conversion exists (are you
missing a cast?)

On this line:

class ListViewItemComparer : IComparer<object>

I added the "<object>" part to get VS to accept it. As can be seen, I'm
clueless about things ending with <>, and for now, I'm quite happy with
the cut-and-paste programming. Just hope someone can spot the error.

Gustaf
 
B

Bob

Hi Gustaf,
This compiles, whether it sorts or not haven't tried.
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)

{

this.listView1.ListViewItemSorter =

new ListViewItemComparer(e.Column);


}

class ListViewItemComparer : IComparer

{

private int col;

public ListViewItemComparer()

{

col = 0;

}

public ListViewItemComparer(int col)

{

this.col = col;

}

public int Compare(object x, object y)

{

return String.Compare(((ListViewItem)x).SubItems[col].Text,

((ListViewItem)y).SubItems[col].Text);

}

}

hth

Bob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top