sara adly
sara adly

Reputation: 297

How to filter datatable

I have this datatable saved in cache

 DataTable dataTable = ReportsBLL.GetProducts() as DataTable;
 HttpContext.Current.Cache["productinfokey"] = dataTable;
 System.Web.HttpContext.Current.Cache.Insert("productinfokey", dataTable, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);

Sometimes I need to filter datatable as

dataTable.Select("CreateDate >= " + DateTime.Now.AddMonths(-3) + " and CreateDate <= " + DateTime.Now + "")

but how can I filter data by those property because this way give me error Syntax error: Missing operand after '05' operator.

datatable filled from

 DataTable table = new DataTable();
 try
 {
      SqlCommand cmd = (SqlCommand).Database.Connection.CreateCommand();

      cmd.CommandText = "[dbo].[Report_Get]";
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@parmCategory", parmCategory);

      try
      {
           Connection.Open();
           var reader = cmd.ExecuteReader();
           table.Load(reader);
           return table;
      }
      catch { /*some other code*/ }
 }
 catch { /*some other code*/ }

What is wrong here and how can I solve this?

Upvotes: 1

Views: 103

Answers (1)

David
David

Reputation: 218808

This:

"CreateDate >= " + DateTime.Now.AddMonths(-3)

Would produce something like this (depending on culture settings, of course, but that's not important here):

CreateDate >= 12/28/2015

Which is a syntax error. Date values need to be wrapped in quotes:

CreateDate >= '12/28/2015'

So you'd need to account for that in the string:

"CreateDate >= '" + DateTime.Now.AddMonths(-3) + "'"

Upvotes: 1

Related Questions