views:

3038

answers:

5

In c#.net I have the following DataSource setup that I am trying to dynamically assign a WHERE clause to in the code behind...

<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
     ContextTypeName="MyNameSpace.DataClasses1DataContext"
     TableName="MyTableWithADateTimeColumn" >
</asp:LinqDataSource>

The code behind looks something like this...

LinqDataSource1.Where = "MyDateColumn == DateTime(" + DateTime.Now + ")";

This gives me an error of "')' or ',' expected". I've also tried casting it inside quotation marks as well as without casting it as DateTime and with quotation marks...

LinqDataSource1.Where = @"MyDateColumn == """ + DateTime.Now + @""" ";

This gives me "Operator '==' incompatible with operand types 'DateTime' and 'String'". I've tried several other ways but I am obviously missing something here.

Similar code is working fine for strings.

+2  A: 

I believe you need to include double quotes around the string being converted to a DateTime.

LinqDataSource1.Where = "MyDateColumn == DateTime(\"" + DateTime.Now.ToString() + "\")";
Reed Copsey
I had tried single quotes without the cast but hadn't thought to try them with the DateTime cast. Unfortunately it gives the error "Character literal must contain exactly one character"
BrianG
Ahh, yeah - needs to be double quotes. Editting...
Reed Copsey
+2  A: 

is it this? What about this then...

LinqDataSource1.Where = "MyDateColumn == DateTime.Parse(" + DateTime.Now + ")"; 
//can't create a date from string in constructor use .Parse()...
J.13.L
take a look again... there is no new DateTime(string value) constructor you need to use DateTime.Parse(string value)...
J.13.L
With the DateTime in double quotes this works.
BrianG
A: 

So the final solution as suggested by J.13.L looked like this...

LinqDataSource1.Where = @"MyDateColumn == DateTime.Parse(""" + MyDateTime + @""") ";

But since I didn't want to match on the time part of the date it really looked more like this...

LinqDataSource1.Where = @"MyDateColumn >= DateTime.Parse(""" + MyDateTime + @""") AND MyDateColumn < DateTime.Parse(""" + MyDateTime.AddDays(1) + @""")";
BrianG
A: 

Another programmatically way:

dataSource.WherePredicateParameters.Clear();
OrExpressionParameter expression = new OrExpressionParameter();
expression.Parameters.Add("Birthday", DbType.DateTime, Convert.ToDateTime(txtBirthday.Text).ToString());
dataSource.WherePredicateParameters.Add(expression);
+1  A: 

LinqDataSource1.Where = "MyDateColumn == Convert.ToDateTime(\"" + DateTime.Now + "\")";

Venugopal