简体   繁体   English

无法对System.String和System.DateTime执行'>'操作

[英]Cannot perform '>' operation on System.String and System.DateTime

I'm trying to filter my DataView by date: 我正在尝试按日期过滤我的DataView:

DataTable dt = GetTableData();
DataView dvEvents = dt.DefaultView;
dvEvents.RowFilter = "date > #" + DateTime.Now.ToString() + "#";

But I'm getting this error: 但是我收到了这个错误:

Cannot perform '>' operation on System.String and System.DateTime. 无法对System.String和System.DateTime执行'>'操作。

I've also tried DateTime.Now.ToString("MM/dd/yyyy") , and I get the same error. 我也试过DateTime.Now.ToString("MM/dd/yyyy") ,我得到了同样的错误。

What am I doing wrong here? 我在这做错了什么?

If you are using string values you need to replace the # with ' . 如果您使用字符串值,则需要将#替换为'

For example: 例如:

dvEvents.RowFilter = "date > '" + DateTime.Now.ToString() + "'";

See this reference 请参阅此参考

It looks like date is defined as a string. 看起来date定义为字符串。 You have two options. 你有两个选择。

You can either make sure string is stored in yyyyMMdd format (so that sorting and filtering works properly) and filter such as: 您可以确保字符串以yyyyMMdd格式存储(以便排序和过滤正常工作)并过滤,例如:

 dvEvents.RowFilter = "date > '" + DateTime.Now.ToString("yyyyMMdd") + "'";

OR you can turn date into actual DateTime column and keep you current code 或者您可以将date转换为实际的DateTime列,并保留当前代码

如果日期来自数据库,则必须在进行比较之前进行区域设置转换。

I had a similar issue and none of the already suggested resolutions worked. 我有一个类似的问题,没有一个已经提出的决议有效。 A work around was to use 一个解决方法是使用

DataTable dt = GetTableData();
DataView dvEvents = dt.DefaultView;
dvEvents.RowFilter = "date > '" + DateTime.Now.ToString("MM/dd/YYYY") + "'";

Hope this helps someone. 希望这有助于某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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