Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 763
Dennis Röttger Avatar asked Dec 06 '22 23:12

Dennis Röttger


2 Answers

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...
}
like image 146
Frédéric Hamidi Avatar answered Jan 03 '23 08:01

Frédéric Hamidi


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.

like image 40
SIbghat Avatar answered Jan 03 '23 08:01

SIbghat