Make locale-aware methods use a new culture at runtime in C#


The example Change program locale at runtime in C# explains how to change a program’s locale and reload its controls for the new locale. However, that doesn’t change the thread’s current culture, which determines the formats used by locale-aware methods such as ToString.

This example uses the following code to change both the program’s current culture and UI culture.

// Set the form's culture.
private void SetCulture(string culture)
    // Make the CultureInfo.
    CultureInfo culture_info = new CultureInfo(culture);

    // Set the thread culture and UI culture.
    Thread.CurrentThread.CurrentUICulture = culture_info;
    Thread.CurrentThread.CurrentCulture = culture_info;

    // Make a ComponentResourceManager.
    ComponentResourceManager component_resource_manager
        = new ComponentResourceManager(this.GetType());

    // Apply resources to the form.
        this, "$this", culture_info);

    // Apply resources to the form's controls.
    foreach (Control ctl in this.Controls)
            ctl, ctl.Name, culture_info);

    // Update the date display.
    lblDate.Text = DateTime.Now.ToString("D");

The SetCulture method takes as a parameter the name of the new culture such as en-US or de-DE. It starts by using that name to create a new CultureInfo object to represent the new locale.

Next, the code sets the current thread’s CurrentUICulture and CurrentCulture properties to the new CultureInfo object. This makes locale-aware methods use the new culture.

The code then creates a resource manager, associates it with the new culture, and uses it to reset the form’s controls for the new culture.

Finally, the method uses DateTime.Now.ToString to show the current date in the new culture’s long date format.

When you click the program’s English and German radio buttons, the following code sets the program’s locale appropriately.

private void radEnglish_CheckedChanged(object sender, EventArgs e)

private void radGerman_CheckedChanged(object sender, EventArgs e)

These event handlers simply invoke the SetCulture method passing it the appropriate locale name.

The picture at the top of the post shows the program using the German locale. If you at the bottom left in the picture, you’ll see that the program is displaying the date in the German format.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in internationalization, localization and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.