Siirry sisältöön
tammikuu 10, 2008 / Jussi

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:

  1. 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.
  2. Add the following namespaces to use in the class: System.Globalization and System.Threading.
  3. Add the following to the Application_BeginRequest handler:
    string lang = Request.UserLanguages != null ? (Request.UserLanguages[0] ?? 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.


One Comment

Jätä kommentti
  1. ingiltere ogrenci vizesi / Elo 6 2008 12:29 am

    do you know any information about this in english?


Täytä tietosi alle tai klikkaa kuvaketta kirjautuaksesi sisään:

Olet kommentoimassa -tilin nimissä. Log Out /  Muuta )

Google+ photo

Olet kommentoimassa Google+ -tilin nimissä. Log Out /  Muuta )


Olet kommentoimassa Twitter -tilin nimissä. Log Out /  Muuta )


Olet kommentoimassa Facebook -tilin nimissä. Log Out /  Muuta )

Muodostetaan yhteyttä palveluun %s

%d bloggers like this: