Thursday, November 09, 2006

ObjectDataSource doesn't respect culture on update

I've recently run into an issue with ObjectDataSource, GridView, and alternate cultures. My present client has a Candian office and the project requires selection of a date from a dropdown. When the data binding to the list of possible dates occurs, the data source uses the current culture to format the dates, so I end up with a dropdown whose ListItems have values like "29/10/2006" and "30/10/2006" since they do their dates backwards up there. This is completely expected and is definitely how things should work.

The problem arises when the user clicks the update button and we have to turn that string (dropdown.SelectedValue) back into a DateTime. Here the ObjectDataSource messes up and converts the string back using the InvariantCulture, which throws an exception since "30/10/2006" isn't a valid date.

This Microsoft Connect link summarizes the issue a bit more.

I was unhappy with the workaround posted there so I figured out a better one. Basically we just do the DateTime conversion ourselves, instead of letting the ObjectDataSource handle it.

1. Handle the ObjectDataSource Updating event.
2. In the handler, replace the string input parameter with its culturally aware DateTime equivalent, using something like:

TypeConverter converter =
    TypeDescriptor.GetConverter(typeof(DateTime));
e.InputParameters["DateField"] =
    converter.ConvertFromString(
        e.InputParameters["DateField"] as string);


And that's it.