Im building a datatable with 2 columns with listview and i need to order the datatable by the second column.
It look something like this:
Name – Points
——————
John – 10
Peter – 14
Marcus – 9
So how do I order it by points?
SOLVED!!
private class PointsComparer : IComparer
{
private const int pointsColumnIndex = 1;
public int Compare(object x, object y)
{
ListViewItem listX = (ListViewItem)x;
ListViewItem listY = (ListViewItem)y;
// Convert column text to numbers before comparing.
// If the conversion fails, just use the value 0.
decimal listXVal, listYVal;
try
{
listXVal = Decimal.Parse(listX.SubItems[pointsColumnIndex].Text);
}
catch
{
listXVal = 0;
}
try
{
listYVal = Decimal.Parse(listY.SubItems[pointsColumnIndex].Text);
}
catch
{
listYVal = 0;
}
return (-Decimal.Compare(listXVal, listYVal));
}
}
This worked as a charm for me.
Use ListViewItemSorter property to set custom
IComparerfor your items. Then simply callSort()method:Here is sample of comparer which you can use to compare points:
Or, as I posted previously, you can use comparer by column text from msdn sample.
UPDATE: You can pass desired sort order to instance of your comparer:
Then use it like this: