pikk
pikk

Reputation: 855

Change language of WinForm with resource

I have the following method that changes the language of the winform.

    private void LoadLanguage(string lang)
    {
        foreach (Control c in this.Controls)
        {
            ComponentResourceManager resources = new ComponentResourceManager(typeof(MainForm));
            resources.ApplyResources(c, c.Name, new CultureInfo(lang));
        }
    }

I call this method on the Form_Load method. Inside the form i have a tab control but the tabPage text property does not change. On the other hand the Label are changed correctly to the appropriate language. Any suggestions?

Upvotes: 0

Views: 3531

Answers (1)

Renatas M.
Renatas M.

Reputation: 11820

Remove your method and try to do like this in Program.cs file:

//Add this line
Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageString);
Application.Run(new Form());

Edit:

The main thing why your code not working is that you applying language for form controls. This means that you applying to TabControl control, but TabControl also have controls(tab pages) "inside". So you need to iterate recursively through controls to apply language for all controls and sub controls. Try this code:

private void LoadLanguage(string lang)
{
    ComponentResourceManager resources = new ComponentResourceManager(typeof(main));
    CultureInfo cultureInfo = new CultureInfo(lang);

    doRecursiveLoading(this, cultureInfo, resources);
}

private void doRecursiveLoading(Control parent, CultureInfo cultureInfo,  ComponentResourceManager resources)
{
    foreach (Control c in parent.Controls)
    {
        resources.ApplyResources(c, c.Name, cultureInfo);
        if (c.Controls.Count > 0)
            doRecursiveLoading(c, cultureInfo, resources);
     }
 }

Upvotes: 2

Related Questions