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 =
e.InputParameters["DateField"] =
        e.InputParameters["DateField"] as string);

And that's it.

1 comment:

ernest elda said...

The workaround presented in the MS Connect is using business object. When you are using business object, you cannot do the conversion by handling the ObjectDataSource Updating event, because converting the TextBox value into DateTime value is done BEFORE the Updating event is raised. This is difference when you are using business object and when you are using parameters to update the value.
see Using Parameters with the ObjectDataSource Control