No applicable method 'Parse' exists in type 'DateTime'

c# datetime dynamic-linq

Question

I get the exception "No applicable method 'Parse' exists in type 'DateTime'" when I run the following code:

var truncatedData = new object();
string TableName = "Products";
string ColumnName = cboAdvSearchCol1.Text.ToString();
var rawData = twr.GetType().GetProperty(TableName).GetValue(twr, null);
string query = ColumnName + ">= DateTime.Parse(" + txtAdvSearchVal1.Text +") && " + ColumnName + "< DateTime.Parse("
+ txtAdvSearchVal1.Text +").AddDays(1)";
truncatedData = ((IQueryable<object>)rawData).Where(query).ToList();//I get exception here

while debugging, I get the value of (string) query as "RUNTIMESTAMP>= DateTime.Parse(7/30/2015) && RUNTIMESTAMP< DateTime.Parse(7/30/2015).AddDays(1)" Please note that I am using dynamic linq.

1
2
8/5/2015 3:13:41 PM

Popular Answer

You generate the following code for your dynamic expression: DateTime.Parse(7/30/2015). However, it's not doing what you're expecting.

Since there are no quotes surrounding the date, the expression 7 / 30 / 2015 is interpreted as integer division, like this:

7 / 30 / 2015 = (7 / 30) / 2015 = 0 / 2015 = 0

So, the result is the same as DateTime.Parse(0), but DateTime.Parse only accepts string as an argument. Since a method accepting an int is not found, you get the exception about no applicable method.

The correct way to call it would be:

string query = ColumnName + ">= DateTime.Parse(\"" + txtAdvSearchVal1.Text +"\") && "
    + ColumnName + "< DateTime.Parse(\"" + txtAdvSearchVal1.Text +"\").AddDays(1)";

Notice the extra " symbols to use the date as a string.

1
8/5/2015 3:48:47 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow