When you create a website with ASP.NET 2.0 and use the two-way databinding with an object datasource, you might have come accross this error:
Cannot convert value of parameter 'Created' from 'System.String' to 'System.DateTime'
This happens when you bind a data field with a DateTime datatype to a textbox, either with the BoundField method or with the <%# Bind("...") %> keyword.
One additional requirement for this error to happen is that the user local is set to non-english (respectively the invariant culture).
Digging deeper into the ObjectDataSourceView with Reflector, I found the cause for this strange behavior: The Bind-keyword or the BoundField class formats the string according to a format string. This, by default that a DateTime is displayed in german as follows:
29.11.2006 09:12:24 (e.g. dd.MM.yyyy hh:mm:ss).
When ASP.NET attempts to write back the changes made by the user, it reads the value from the textbox and tries to convert it from a string to a DateTime object. It does this by retrieving the TypeConverter responsible for the DateTime class and calls typeConverter.ConvertFromInvariantString(). This obviously fails with a non-english string and produces the error seen above.
The default.aspx file in the attached Visual Studio Solution shows this error.
Workaround
The workaround I'm using for this issue is to attach an Item_Updating event to the data control (DetailsView, FormView, etc). This event then converts the dataformat to an invariant datetime string:
1 protectedvoid DetailsView1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
2 {
3 e.NewValues["Created"] = DateTime.Parse((string) e.NewValues["Created"]).ToString(CultureInfo.InvariantCulture);
4 }
The solution.aspx file implements this workaround.
Downloads
| TwoWayDataBinding.zip (18,427 Bytes) Example application which demonstrates the described problem and workaround |