Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Column By DateTime Value Not String Value?

I'm using this to sort a list view: http://support.microsoft.com/kb/319401 It's working great, except when I try to sort a date column, it things 2AM comes after 10PM (since 2 is greater than 1).

4/7/2011 10:00:00 PM
4/7/2011 2:00:00 AM

This is the code I'm using:

var lvcs = new ListViewColumnSorter();
ListView.ListViewItemSorter = lvcs;
lvcs.Order = SortOrder.Ascending;
lvcs.SortColumn = 1; //<-Contains DateTime values in string format
ListView.Sort();

So how can I convert to DateTime and sort using the code above?

like image 708
sooprise Avatar asked Oct 16 '25 10:10

sooprise


2 Answers

Look at the "Sorting Dates" section in this article - you replace the Compare method.

Example Code:

try {
    DateTime dateX = Convert.ToDateTime(listviewX.SubItems[ColumnToSort].Text);
    DateTime dateY = Convert.ToDateTime(listviewY.SubItems[ColumnToSort].Text);
    compareResult = ObjectCompare.Compare(dateX, dateY);
}
catch {
    compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
}
like image 128
Cade Roux Avatar answered Oct 19 '25 01:10

Cade Roux


I have done this for years, but just ran across the post.. I noticed Gary did something like it, but I never had a problem with it comparing date so never had to use the DateTime compare object. Guess this is another option for people to chose from.

public int Compare(object x, object y)
{
    int compareResult;

    //added based on madmonk46's comment below.
    if (x == null || y == null)
        return 0;

    //get string values from parameters
    string xVal = ((ListViewItem)x).SubItems[ColumnToSort].Text;
    string yVal = ((ListViewItem)y).SubItems[ColumnToSort].Text;

    //check if values are int, long, double, or floats
    if (float.TryParse(xVal, out float xFloat) && float.TryParse(yVal, out float yFloat))
        compareResult = ObjectCompare.Compare(xFloat, yFloat);
    //check if values are dates
    else if (DateTime.TryParse(xVal, out DateTime xDateTime) && DateTime.TryParse(yVal, out DateTime yDateTime))
        compareResult = ObjectCompare.Compare(xDateTime, yDateTime);
    //compare as strings
    else
        compareResult = ObjectCompare.Compare(xVal, yVal);

    // 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;
    }
}