Search code examples
c#internationalizationcurrency-formatting

How to obtain the control panel currency format in C#


Our report generator works fine when the culture setting uses "$" for currency symbol.

Now we want to use this in European and use "€" instead.

I went to control panel, change the "Region and Language" format to "Danish (Denmark)" and apply the change.

Now open Excel and type in a number then set the cell format to currency, the currency symbol is updated.

However, our report generator is still using "$". When debugging the software we found that CultureInfo.CurrentCulture is still a culture using "$" (i.e., en-AU).

(The code is trivial but I just simply written down here:)

result = ValueToDisplay.ToString("C"); //CultureInfo.CurrentCulture is "en-AU"

I recon this might not be a real problem when the user's computer is in European since in that case CultureInfo.CurrentCulture will be different.

However, obviously Excel can correspond to the setting change in control panel without even reboot the computer, so in theory our software should be able to do so as well.

So how do we work like Excel?


Solution

  • You can handle this without a restart of your application by listening for the event that indicates the locale has changed and then clearing the CultureInfo cache.

    To listen for the event, you can do this:

    SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;
    

    Then in the event handler, you can clear the Culture cache:

    private void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
    {
        if (e.Category == UserPreferenceCategory.Locale)
            CultureInfo.CurrentCulture.ClearCachedData();
    }
    

    Now, when you run code like this:

    var number = 21.00;
    MessageBox.Show(number.ToString("C"));
    

    You will get the correct output based on whatever locale information the user has changed.