Home / WPF / WPF Resources / Multilanguage applications with C# with database support

Multilanguage applications with C# with database support

[5/3/2012: I updated this post with a new version of this library for WPF, keeping this post separated because for Winforms this library is still okay. Check it here]

Download the sample application: http://mesta-automation.com/Downloads/changeLanguage.rar

As i wrote in an earlier post, the best way to realize a multilanguage application is to get translated text from a database.

I think that one of the best database to use for translations is MS Access, because every translator has an office suite installed on his PC, and for him makes no difference translate on Excel or Access, but if you ask him to translate your sentences on “a random SQL data viewer”, it can be a pain.

To support multilanguage in my apps i use a method that, given the name of control, returns a string containing the translated text, like:

lblSample.Content = Translation.GetString("lblSample");

The reference to the culture is contained inside Settings, and that’s where i modify my language preferences, so when i load the program i know automatically what language i should use.

To realize a multilanguage selection you need:

– a listbox containing the list of languages,

– an “Apply” button

Features:

– The listbox should automatically detect the new languages

– The application should change not only the texts, but also date/time format, right to left writing and so on.

1#: Create a database file with access like in the sample and add it to the project:

2#: Download the translation class from

here

and paste it in your project,

or you can download the class with the working sample here:

http://mesta-automation.com/Downloads/changeLanguage.rar

3#: Add the current culture field on “Settings”: this field will be used on all the project to set the national preferences.

4#: Customize the translation class modifying the namespace and the table rererences, if you modified them.

using ChangeLanguage.Properties; // modify the namespace with your project name
[...]
//connection string
 private static DatabaseResourceManager databaseResourceManager = new DatabaseResourceManager(settings.translationsConnectionString);

[...]
OleDbCommand command = new OleDbCommand("Select * From Translations"); // Here there is the reference to table name
[...]
command.CommandText = "SELECT [key], [" + language + "] " + "FROM Translations"; // Here there is the reference to table name

5#: Create the GUI like in the example:

if you use xaml you can use this code:


 <label></label>
 <button name="btnApply"></button>
 <button name="btnButton"></button>
 <label></label>
 <label></label>
 <label></label>

6# Then in the main window you can write methods to fill the language comboBox

///
<summary> Detects languages in database and fill the listbox </summary>
private void LoadCmbItems()
{
    try
    {
        List cultureList = Translations.GetCultureList();
        listLanguages.ItemsSource = cultureList;
        listLanguages.SelectedItem = settings.currentCulture;
        Date = DateTime.Now;
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message, "Language Database error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

and to load / change texts (but usually i do this only on the launch of application)

private void SetTextsInCurrentLanguage()
{
    this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);
    LoadCmbItems();
    lblLanguages.Content = Translations.GetString("lblLanguages");
    btnApply.Content = Translations.GetString("btnApply");
    btnButton.Content = Translations.GetString("btnButton");
    lblLabel.Content = Translations.GetString("lblLabel");
    lblDateTime.Content = Translations.GetString("lblDateTime");
}

You can see that it’s really simple to extract translation with this method, it’s just needed that you pass the name of the control to the method GetString to receice the translated Content.
7#: Once you wrote all translations, you can update the constructor of the main window to load the localized language and settings:

public MainWindow()
{
    Thread.CurrentThread.CurrentCulture = settings.currentCulture;
    Thread.CurrentThread.CurrentUICulture = settings.currentCulture;
    this.DataContext = this;
    InitializeComponent();
    SetTextsInCurrentLanguage();
}

and also create the button “Apply”, that basically changes the settings (and in the example refresh the GUI also) :

private void btnApply_Click(object sender, RoutedEventArgs e)
{
    settings.currentCulture = (CultureInfo)listLanguages.SelectedItem;
    Thread.CurrentThread.CurrentCulture = settings.currentCulture;  //not so good to see... just to explain how it works
    Thread.CurrentThread.CurrentUICulture = settings.currentCulture;//you should force the user to re-initialize the program
    SetTextsInCurrentLanguage();
}

You can download the full example here:

http://mesta-automation.com/Downloads/changeLanguage.rar

and read the full documentation here:

http://en.csharp-online.net/Localization_Like_the_Pros 

Disclaimer

The sample code described herein is provided on an “as is” basis, without warranty of any kind, to the fullest extent permitted by law.

Share Button

12 comments

  1. Great post! I’d like to point out that instead of implementing your own database for localization, WPF provides its own service in the form of resource files. Here’s the definitive Microsoft Guide to WPF Globalization and Localization. Even if you’re not sure if you want to provide localization in the future, it’s good practice to store your literal strings in .resx files anyway. That way, adding localization in the future shouldn’t affect your code.

  2. Thanks for the advice Scott, i’ll check that out 🙂
    I got used to translations like in WinCC, where you had a table with all languages, so i thought this was the best way for external translators to translate an application.
    I’ll try the resx method for sure.
    Congratulations for your awesome blog, i always check it and it’s a mine of knowledge !!! You are doing an excellent job sharing such knowledge with us !

  3. hi
    i cannot find Culture Type in C# Settings
    How u add it
    thanks
    farzad

    • In solution Explorer, right click on the project, then properties. In the window that opens, there you find a tab with settings. But you probably better check google for c# settings to understand better.

      • Misunderstanding happens.
        i Know where exactly settings is , in C#
        but The Type of Culture you Created is not on the list of Types

        • You can click browse on the bottom of the list of types, then expand mscorlib and there you find system.globalization.cultureInfo. Hope it’s correct because at the moment I don’t have visual studio here.

        • at first thanks for your fast reply
          that’s the point , i cannot find even in browse.
          Maybe something should be add in project resources ???

        • After you click browse,you can try to type System.Globalization.CultureInfo directly in the text and press ok, without expanding anything. If this doesn’t work I should check visual studio but will be next week. Also you should check if you are using .Net 4.0. I don’t know about earlier versions of the framework.

        • Ok thanks it accepted but
          now , in translate class i have 2 error in
          settings.translationsConnectionString
          and
          CultureNotFoundException

        • You have to try to guess yourself. When I’ll be home I’ll try to download the example and check what’s wrong. This will be next week.

        • ok thanks for your time

Leave a Reply