ASP.NET, ObjectDataSource and DateTime Culture Problems
If you want to display and especially provide editing capabilities for DateTime data in ASP.NET applications, you’ll surely sooner or later run into problems.
Without any exact format specifiers, your DateTime data may display in a wrong format, but this can be corrected by providing your desired format string to the binding expression.
However, when you edit a DateTime value e.g. in a TextBox, you’ll soon start getting ”Could Not Convert” exceptions. It turns out that, initially, ObjectDataSource uses the default Culture of the current thread to convert DateTimes to and from strings, and that Culture is the Culture of the server, not the user agent.
There are some commonly seen solutions to this that recommend forcing conversions in the right format in your data control’s Updating event handler.
A cleaner solution that also removes the need to specify explicit format strings is to adopt the user’s Culture as the server Thread’s Culture and UICulture. Here’s how:
- Add a Global class to your Web Client project by going to Add New Item and selecting Global Application Class. Global.asax will be created with its code-behind class Global.asax.cs.
- Add the following namespaces to use in the class: System.Globalization and System.Threading.
- Add the following to the Application_BeginRequest handler:
string lang = Request.UserLanguages != null ? (Request.UserLanguages ?? string.Empty) : string.Empty; CultureInfo info = CultureInfo.CreateSpecificCulture(lang); Thread.CurrentThread.CurrentCulture = info; Thread.CurrentThread.CurrentUICulture = info;
2008-01-11 Fixed a possibility for ArgumentNullException in CreateSpecificCulture.