问题
I am using c#.net. Thanks in advance for any help.
I am using a Repeater and a ObjectDataSource. I use LINQ to connect to the database. This requires a parameter to be passed through (used within the WHERE clause)
public IQueryable<comments> GetComments(DateTime todaysDate)
{
return (from c in dc.comments
where displayDate.Date == todayDate.Date
select c);
}
I am encounting the error above and don't know why. Here is where the problem lies:
<asp:Parameter DefaultValue="<%=Convert.ToDateTime(DateTime.Now)%>" Name="todayDate" Type="DateTime" />
If I provide a actual date it works. For example:
<asp:Parameter DefaultValue="02/09/2009" Name="todayDate" Type="DateTime" />
I have also tried the following and recieved the same error:
DateTime.Now.Date
Datetime.Now
Datetime.Today
Datetime.Now.ToString
Datetime.Now.Date.ToString.
What am I doing wrong?
Thanks
Clare
回答1:
Using <%= .. %> syntax in a server control () is not possible. Use code-behind to set the property.
回答2:
You can add the SelectParameter in the page load. Just add this -
SqlDataSource1.SelectParameters["todayDate"].DefaultValue = Datetime.Now;
Edit: Thanks Hans for the correction.
回答3:
If you've copied and pasted your code, then you might have a typo in the function - the function parameter is named todaysDate, but the where statement uses todayDate (which is your ASP parameter).
If this is not the case, please post where you call your GetComments function from.
回答4:
Are you sure this is the correct location of the error? Here is what Convert.ToDateTime does:
public static DateTime ToDateTime(bool value)
{
return ((IConvertible) value).ToDateTime(null);
}
DateTime is an IConvertible, and it implements ToDateTime very simply:
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return this;
}
As Chris pointed out, there is no reason to convert DateTime.Now to a DateTime. It already is one.
回答5:
Thank you everyone for you help. You put me on the right track.
After finding out I could set the DefaultValue within the code behind I have another look around the web and found this tutorial.
This is now working.
Here is my code:
protected void comments_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["todayDate"] = DateTime.Now;
}
However please note first you must create a 'Selecting' event (within the properties tab).
I hope this is the correct way of doing it. Does anyone have any comments on this?
Thanks again
Clare
来源:https://stackoverflow.com/questions/1368064/system-formatexception-string-was-not-recognized-as-a-valid-datetime