Search code examples
c#asp.netuser-controlsresourcesascx

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


Solution

  • 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...
    }