Search code examples
c#sortinglistview

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?


Solution

  • 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);
    }