使用linq解决日期时间错误



我怎么用Linq做到这一点?我试过了,但没有成功

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;
    }
}

我试了一下,但它不工作

syntaxerroreexception未被用户代码处理包含无效的名称:[].

另一个尝试

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();  

以下是如何使用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;
}

相关内容

  • 没有找到相关文章

最新更新