2016-09-01 17 views
0

我有一個組合框包含這些年來,Exampple:2016,2017,2018等如何在我的案例中查找包含數據表中匹配字符串的行?

我有DT其中有5 columnc其中包含日期3列,其是按名稱paydate,BEGINDATE,結束日期。但是每個日期的格式是dd/mm/yyyy。

我該怎麼辦?

我必須在組合框(cboYear)中找到包含所選年份的所有行。如果在數據表的行中只有幾年,但它的日期和月份是「/」 ,因此它不能匹配字符串「2016」和「01-12-2016」,並返回no行由如下因素查詢:

//this cboYear.Text has lets say "2016 and paydate and other two column has date in format "dd/mm/yyyy"" 
DataRow[] foundAuthors = dt2.Select("paydate= '" + cboYear.Text + "'" + " and " + "begindate= '" + cboYear.Text + "'" + " and " + "enddate= '" + cboYear.Text + "'"); 
if (foundAuthors.Length != sdgvPayDates.Rows.Count-1) 
{ 
     MessageBox.Show("All rows must have same year as the selected year in combobox"); 
     return false; 
} 

如何獲得它包含找到有效匹配selcted年行?

如果像LINQ中的「like」運算符那樣的東西也存在?這樣它就可以找到所有匹配的行,以便即使「2016」數據表包含01/02/2016格式時也能找到該行。 DataTable包含此http://prntscr.com/ccx3zn

+0

你是否試過'DateTime.Now.Year'從你的日期獲得你的年? –

+0

日期在數據表中我不能更改數據表中的格式 – stack

+0

你能分享你的'DataTable'代碼嗎? –

回答

1
string stringDate= "01-12-2016"; 
DateTime date = DateTime.Parse(stringDate); 
int year = date.Year; 

可以解析您的日期DateTime並提取一年

編輯: 你可以嘗試下面的代碼段提到的辦法,我已經使用LINQ獲得數據表中所需的數據行。

DataTable dt = new DataTable(); 
dt.Columns.Add("dateColumn"); 
DataRow row = dt.NewRow(); 
row[0] = "01-12-2016"; 
dt.Rows.Add(row); 

int year = 2016;    
DataRow[] foundAuthors = dt.AsEnumerable().Where(r => DateTime.Parse(r.Field<string>("dateColumn")).Year == year).ToArray(); 
+0

請重新閱讀該問題。我通過匹配一個只有年份格式「yyyy」的字符串在數據表中找到包含日期的數據表中的行。 – stack

+0

@stack讓我知道如果我的第二種方法對您有用或沒有! !! :) – Sagar

0

在您的select語句中,您要選擇全年。因此,請選擇當年1月1日之後和明年1月1日之前的日期。

int nextyear = Int32.Parse(cbo.Year) + 1; 
DataRow[] foundAuthors = dt2.Select("paydate>='" + cboYear.Text + "-01-01' and paydate<"+ nextyear + "-01-01 ' and begindate>='" + cboYear.Text + "-01-01' and begindate<" + nextyear + "-01-01' and enddate>= '" + cboYear.Text + "-01-01' and enddate<" + nextyear + "-01-01';"); 
相關問題