I am having a problem with sorting a multi-column ListBox. For simplicity, let's say I only have 3 columns: Id, Score, and TotalPoints. I have implemented a Compare method from the IComparer interface that looks like this:
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (
ListViewItem)x;
listviewY = (
ListViewItem)y;
// Compare the two items
compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
}
The sorting is inaccurate though. For example, let's say I have 3 rows, and the Scores are 10, 11, and 2. When I sort the column, it displays 10, 11, then 2...not 11, 10, 2. I am pretty sure it has something to do with the number of digits in the string, but I have no idea how to resolve it. For the most part the sorting works, just this little kink. Any help would be greatly appreciated.
Thanks