使用c# DataView.字符串类型的函数参数上的RowFilter属性
本文关键字:参数 RowFilter 属性 函数 使用 DataView 字符串 类型 | 更新日期: 2023-09-27 18:01:37
是否有办法在以下string
变量上使用DataView
的Rowfilter
属性?
public DataTable FilterByLatestDate(DataTable tbl, string date_asof)
{
DataView latest = tbl.DefaultView;
//latest.RowFilter = "[date]= '" + date_asof + "'" ; //
//latest.RowFilter = string.Format("[date]= '{0}'", date_asof); // alternative to messing around with quotes
DataTable last_tbl = latest.ToTable();
return last_tbl;
}
Ps:我是只有感兴趣的建议涉及.Rowfilter
当您在RowFilter中使用Date时,要使用的引号字符是#符号
latest.RowFilter = "[date]= #" + date_asof + "#" ;
然而,RowFilter属性接受字符串,因此当您使用日期作为过滤器时,变量应该以"MM/dd/yyyy"的格式表示。因此,如果您的字符串date_asof
不是这种格式,则此代码无法正常工作。
我建议你传递一个DateTime给你的函数,然后用
格式化它public DataTable FilterByLatestDate(DataTable tbl, DateTime date_asof)
{
DataView latest = tbl.DefaultView;
latest.RowFilter = "[date]= #" + date_asof.ToString("MM/dd/yyyy") + "#";
return latest.ToTable();
}