[英]How to use Row filter on DataView
我有數據表,該表具有一列名為joiningDate
,其格式為mm-dd-yyyy
。 我想根據當前月份過濾該表,因此我將DataView
用於此類操作,我的代碼是:
DateTime now = DateTime.Now;
DataView dvUpcomingLeave = new DataView(dtLeaves);
dvUpcomingLeave.RowFilter = "DATEPART(Month, joiningDate) = " + now.Month;
但是它向我顯示錯誤:
該表達式包含未定義的函數調用DATEPART()。
我認為因為DATEPART()
不是ADO.NET的功能,所以任何人都可以幫助我如何僅使用DataView
RowFilter
解決此問題。
您不能使用RowFilter
表達式提供的功能(用於DataColumn的Expression屬性的功能)來做到這一點
但是,您可以通過以下方式實現目標
DataView v = dtLeaves.AsEnumerable()
.Where(x => x.Field<DateTime>("joiningDate")
.Month == DateTime.Today.Month)
.CopyToDataTable().DefaultView;
警告,如果Where
返回的輸入IEnumerable為空,則此CopyToDataTable將失敗,因此最好將其分成多行並測試結果,然后再繼續下一步
var temp = dtLeaves.AsEnumerable()
.Where(x => x.Field<DateTime>("joiningDate")
.Month == DateTime.Today.Month);
if(temp.Any())
DataView dvUpcomingLeave = temp.CopyToDataTable().DefaultView;
您必須將Date-Values放在引號或#標簽中( 來源:csharp-examples.net )
因此,在您的情況下:
dvUpcomingLeave.RowFilter = String.Format("DATEPART(Month, joiningDate) = '{0}'",now.Month);
要么
dvUpcomingLeave.RowFilter = String.Format("DATEPART(Month, joiningDate) = #{0}#",now.Month);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.