Wednesday, May 21, 2008

Change ASP.NET User Control UICulture

Illlustration: language Sometimes you have to change the culture settings of a user control in runtime. Let's say we have to change the language of a login form on user click. Let's say we do not want to and cannot change the culture of the page (e.g.  the user control is embedded in a SharePoint page).

The first step is to create a Local Resource for the user control (.resx). Now it's possible to change the language dynamically.

The next step is to put buttons on the form and create event handlers for each languages. The standard code to change the culture is something like this:

System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("hu-HU");

Unfortunately we will not be successful this way.

The solution is to override the FrameworkInitialize() method and set the Thread.CurrentThread.CurrentUICulture inside that.

You will probably have to use Session state to store the current language. If we set the Session variable in an event handler, we will have to click twice on the button to change the language of the form. The trick is  the following:

Server.Transfer(Request.Url.PathAndQuery, false);

Now the user control will appear with the selected culture settings after pressing the button.