[英]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). 我正在使用它来对列表视图进行排序: http : //support.microsoft.com/kb/319401它工作得很好,除非我尝试对日期列进行排序,它将在晚上10点之后出现2AM(因为2大于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? 那么如何转换为DateTime并使用上面的代码进行排序?
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:
为了避免使用try / catch和捕获抛出的exeptions,我使用了以下内容并且它完美地工作:
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. 您应该从列表视图中获取项目并将日期/时间字符串转换为DateTime对象,然后对这些对象调用sort(将它们放入集合中),然后将它们放回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, 尝试转换为DateTime和Create
List<DateTime>
然后对其进行排序,
You can use DateTime.TryParse
or ParseExact to specify you own parsing format 您可以使用
DateTime.TryParse
或ParseExact指定您自己的解析格式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.