在BindingSource中过滤DateTimePicker的日期值

时间:2012-01-30 01:47:34

标签: c# filter bindingsource

bsCheckVoucherGridView.Filter = 
    string.Format("[CHECK DATE] >= #{0:M/dd/yyyy}# ", 
    dateTimePicker_CheckVoucher_SearchCheckVoucherDate.Value);    
dateTimePicker_CheckVoucher_SearchCheckVoucherDate.Value = DateTime.Now.AddYears(-1);
dateTimePicker_CheckVoucher_SearchCheckVoucherDate.Format = DateTimePickerFormat.Short;
bsCheckVoucherGridView.DataSource = 
    db.GetDataTable("SELECT `CHECK_DATE` AS `CHECK DATE` FROM check_voucher");
bsCheckVoucherGridView.Filter = 
    string.Format("[CHECK DATE] >= {0:M/dd/yyyy} ",
    dateTimePicker_CheckVoucher_SearchCheckVoucherDate.Value);

上面的代码在System.DateTime和System.Double上发出了“无法执行'> ='操作错误。”

我要回答我的问题。

bsCheckVoucherGridView.Filter = 
    string.Format("[CHECK DATE] >= #{0}# ", 
    dateTimePicker_CheckVoucher_SearchCheckVoucherDate.Value.ToString("dd-MMM-yyyy"));

这完美无缺!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

  // Setup Filter and Sort Criteria
  strExpr = "OrderDate >= '01.03.1998' AND OrderDate <= '31.03.1998'";
  // OR
  // strExpr = "OrderDate >= #01.03.1998# AND OrderDate <= #31.03.1998#";
  strSort = "OrderDate DESC";

  // Use the Select method to find all rows matching the filter.
  foundRows = myTable.Select(strExpr, strSort);

完整代码

private void BtnFilterAndSort_Click(object sender, System.EventArgs e)
{
  string  strText;
  string  strExpr;
  string  strSort;
  DataRow[] foundRows;
  DataTable myTable;
  myTable = ds.Tables["Orders"];

  // Setup Filter and Sort Criteria
  strExpr = "OrderDate >= '01.03.1998' AND OrderDate <= '31.03.1998'";
  strSort = "OrderDate DESC";

  // Use the Select method to find all rows matching the filter.
  foundRows = myTable.Select(strExpr, strSort);

  // Apply all Columns to the TextBox, this
  // must be done Row-By-Row.
  strText = null;
  for (int i = 0 ; i <= foundRows.GetUpperBound(0); i++)
  {
    for (int j = 0; j <= foundRows[i].ItemArray.GetUpperBound(0); j++)
    {
      strText = strText + foundRows[i][j].ToString() + "\t";
    }
    strText = strText + "\r\n";
    textBox.Text = strText;
  }
}