2013-02-27 71 views
0

我該如何與Linq做到這一點? 我試過沒有成功用linq解決DateTime錯誤問題

protected void Calendar1_SelectionChanged(object sender, EventArgs e) 
{ 
    DataView view = socialEvents.DefaultView; 
    view.RowFilter = String.Format(
         "Date >= #{0}# AND Date < #{1}#", 
         Calendar1.SelectedDate.ToShortDateString(), 
         Calendar1.SelectedDate.AddDays(1).ToShortDateString() 
        ); 

    if (view.Count > 0) 
    { 
     DataGrid1.Visible = true; 
     DataGrid1.DataSource = view; 
     DataGrid1.DataBind(); 
    } 
    else 
    { 
     DataGrid1.Visible = false; 
    } 
} 

我嘗試這一點,但它doen't工作

SyntaxErrorException是由用戶代碼未處理的表達 包含無效名稱:[]。

闖闖

var rows = socialEvents.Rows.Cast<DataRow>() 
      .Where(r => (DateTime)r["Date"] >= Calendar1.SelectedDate.Date && 
         (DateTime)r["Date"] <= Calendar1.SelectedDate.AddDays(1)) 
       .ToArray(); 
view.RowFilter = rows.ToString(); 
+0

試圖Convert.ToDateTime(R [ 「日」] )? – jbl 2013-02-27 10:19:16

+0

是的,我只是試試! – 2013-02-27 10:27:57

回答

1

這裏是你應該如何使用RowFilter

view.RowFilter = String.Format(
        "Date >= #{0}# AND Date < #{1}#", 
        Calendar1.SelectedDate.ToString("MM/dd/yyyy"), 
        Calendar1.SelectedDate.AddDays(1).ToString("MM/dd/yyyy")); 

或者與LINQ

var table = (from r in socialEvents.AsEnumerable() 
      where r.Field<DateTime>("Date") >= Calendar1.SelectedDate.Date 
        r.Field<DateTime>("Date") <= Calendar1.SelectedDate.AddDays(1) 
      select r).CopyToDataTable(); 

if (table.Rows.Count > 0) 
{ 
    DataGrid1.Visible = true; 
    DataGrid1.DataSource = table; 
    DataGrid1.DataBind(); 
} 
else 
{ 
    DataGrid1.Visible = false; 
} 
+0

是的,這是一個數據表,但你的解決方案不工作 – 2013-02-27 10:24:32

+0

@ user2046944什麼意思*不起作用*?例外?哪個例外? – 2013-02-27 10:25:16

+0

view.RowFilter = rows; 不能將類型'System.data.enumerableRowCollection '隱式轉換爲'字符串' – 2013-02-27 10:33:13