V
Visual Systems AB \(Martin Arvidsson\)
Hi!
I am using the IComparer interface to sort items in a ListView, what I am
trying to figure out
is how can the method Compare know how to get the 1st and 2nd value in the
listview, then the 3rd and 4th, and so on?
What is telling the Compare object to do this? Is there a foreach in the
IComparer interface that handles this? How can the IComparer recognize the
list?
Code below
Regards
Martin
private void lvMail_ColumnClick(object sender,
System.Windows.Forms.ColumnClickEventArgs e)
{
this.sortListAscending = !this.sortListAscending;
this.lvMail.ListViewItemSorter = new ListViewItemComparer(e.Column,
sortListAscending);
lvMail.Sort();
}
}
class ListViewItemComparer : IComparer
{
private int col;
private bool _ascending;
public ListViewItemComparer()
{
col=0;
_ascending=true;
}
public ListViewItemComparer( int column, bool ascending )
{
col=column;
_ascending=ascending;
}
public int Compare(object x, object y)
{
if( _ascending )
return String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
else
return String.Compare(((ListViewItem)y).SubItems[col].Text,
((ListViewItem)x).SubItems[col].Text);
}
}
I am using the IComparer interface to sort items in a ListView, what I am
trying to figure out
is how can the method Compare know how to get the 1st and 2nd value in the
listview, then the 3rd and 4th, and so on?
What is telling the Compare object to do this? Is there a foreach in the
IComparer interface that handles this? How can the IComparer recognize the
list?
Code below
Regards
Martin
private void lvMail_ColumnClick(object sender,
System.Windows.Forms.ColumnClickEventArgs e)
{
this.sortListAscending = !this.sortListAscending;
this.lvMail.ListViewItemSorter = new ListViewItemComparer(e.Column,
sortListAscending);
lvMail.Sort();
}
}
class ListViewItemComparer : IComparer
{
private int col;
private bool _ascending;
public ListViewItemComparer()
{
col=0;
_ascending=true;
}
public ListViewItemComparer( int column, bool ascending )
{
col=column;
_ascending=ascending;
}
public int Compare(object x, object y)
{
if( _ascending )
return String.Compare(((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
else
return String.Compare(((ListViewItem)y).SubItems[col].Text,
((ListViewItem)x).SubItems[col].Text);
}
}