Dennis Röttger
Dennis Röttger

Reputation: 1985

Programmatically set Culture of User Controls in ASP.NET

I'd like to programmatically set the culture of my User Control which defines several Labels, Buttons and Textboxes ...

Usually, for aspx-pages you override the InitializeCulture-Method and set Culture and UICulture to achieve this, alas ASCX-Controls do not have this Method, so how exactly would I do this?

I've set up the local resources mycontrol.ascx.de-DE.resx, mycontrol.ascx.resx and mycontrol.ascx.en-GB.resx but only the values of the default file (mycontrol.ascx.resx) are used.

Thanks in advance.

Dennis

Upvotes: 4

Views: 11870

Answers (3)

SIbghat
SIbghat

Reputation: 309

I also spent hours on this problem and finally got This solution. You only have to override the FrameworkInitialize() instead of initilizeculture(), eg:

protected override void FrameworkInitialize()
{
    String selectedLanguage = LanguageID;
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedLanguage);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage);

    base.FrameworkInitialize();
}

Jus Put this code inside your ascx.cs file, This override function does not need to be called.

Upvotes: 6

fatih
fatih

Reputation: 21

I used the following code to change the language for asp.net mvc in my project page

public ActionResult ChangeCulture (Culture lang, string returnUrl)
     {
         if (returnUrl.Length> = 3)
         {
             returnUrl = returnUrl.Substring (3);
         }
         return redirect ("/" + lang.ToString () + returnUrl);
     }

also I used usercontrol (ascx) on the same page.when I changed language with actionlink is changed viewpage language but user control pageload event isn't capture changing so viewpage's language changes but usercontrol's language doesn't change

Upvotes: 2

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

The current culture is thread-wide: Page.Culture and Page.UICulture actually set Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture under the hood.

If the user control is defined in your page markup, I don't think there's anything you can do. If you load it with LoadControl(), you can temporarily override the current thread's culture before the call and restore it afterward, but it would be quite awkward:

protected void Page_Load(object sender, EventArgs e)
{
    // Some code...

    CultureInfo oldCulture = Thread.CurrentThread.CurrentCulture;
    CultureInfo oldUICulture = Thread.CurrentThread.CurrentUICulture;
    Thread.CurrentThread.CurrentCulture = yourNewCulture;
    Thread.CurrentThread.CurrentUICulture = yourNewUICulture;

    try {
        Controls.Add(LoadControl("yourUserControl.ascx"));
    } finally {
        Thread.CurrentThread.CurrentCulture = oldCulture;
        Thread.CurrentThread.CurrentUICulture = oldUICulture;
    }

    // Some other code...
}

Upvotes: 6

Related Questions