Change a localized program's locale at runtime to test it in multiple languages and locales in C#

The example Localize a program's user interface to work in multiple languages and locales in C# explains how to localize a program so it displays different user interfaces depending on the system's locale. The example Test a localized program that works in multiple languages and locales in C# explains how you can select a specific locale when the program starts so you can test different locales.

This example lets you select a specific locale at run time.

The SetCulture method shown below selects a specific culture.

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

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

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

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

The code makes a new CultureInfo object to represent the culture. It then makes a ComponentResourceManager for the culture and uses its ApplyResources method to load the culture-specific resources for the form and its controls.

The following code shows how the example loads its resources for English or German when you select a radio button.

private void radEnglish_Click(object sender, EventArgs e)
{
SetCulture("en-US");
}

private void radGerman_Click(object sender, EventArgs e)
{
SetCulture("de-DE");
}

(This example actually isn't localized for English but that's what I used when making the default localization so that's what you get if you select en-EN or any other culture for which it isn't localized. For example, try fr-FR or es-MX.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.