简体   繁体   中英

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?

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

The answer marked as correct here did not help me. My app seemed to go in to an infinite loop of thrown exceptions. To avoid using a try/catch and catching thrown exeptions, I used the following and it works perfectly:

DateTime dateX;
DateTime dateY;
if (
    DateTime.TryParse(listviewX.SubItems[ColumnToSort].Text, out dateX)
    && DateTime.TryParse(listviewY.SubItems[ColumnToSort].Text, out dateY)
    )
{
    compareResult = ObjectCompare.Compare(dateX, dateY);
}
else
{
    compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
}

You should get your items from your listview and convert the date/time strings to DateTime objects and then call sort on those objects (having put them in a collection) and then put them back into your ListView.

Hopefully that solves your issue.

above is correct because you are doing string comparison of list.

try to convert to DateTime and Create List<DateTime> and sort it then,

You can use DateTime.TryParse or ParseExact to specify you own parsing format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM