views:

29

answers:

2

If I have a single label on my ASP.NET (2.0) page, and I want to store an error message in it; and if I do that in code by making multiple IF statements, like:

if (...)
 value = "..."
else
 value = "......"
etc

how would I localize this, so that I don't have to write:

if (...)
{
     switch(langCase)
     {
        case "en-US":
          value = "englishValue";
          break;
        case "de-CH":
          value = "german Swiss value";
          break;

             ...
     }
}
else
{ 
   switch(langCase)
     {
        case "en-US":
          value = "englishValueForElse";
          break;
        case "de-CH":
          value = "german Swiss value for ELSE";
          break;

             ...

     }
}

If I create multiple label controls for each if-else case, I will have to hide all but the one for the current language (ugly? ). What I would like is a kind of resource file, but with rows for each case that could happened, and columns for each language needed.

+3  A: 

You should use a resource file (.resx) in order to store your messages. ASP.NET has built in localization mecanisms using resources.

In order to add resources to your application, You have only to add a new "Resource element" using the Add new item dialog box.

If your resx file is called ApplicationStrings.resx, the ErrorLabel string contained in it would be accessible in your website through the property

ApplicationStrings.ErrorLabel

(VS generates a class to encapsulate the resx file)

You can support localization with strings by creating new Resources with adequate naming:

ApplicationStrings.fr.resx will contain the french localization of ApplicationStrings.resx ApplicationStrings.fr-fr.resx will contain the french/France localization, etc...

ASP.NET handle fallback, then if ErrorLabel is absent from ApplicationStrings.fr-fr.resx (or ApplicationStrings.fr-fr.resx does not exist), it will look for it in ApplicationStrings.fr.resx, then in ApplicationStrings.resx .

It's worth noting too that ASP.NET use the current thread culture to perform localization in resources. You must therefore ensure that System.Threading.Thread.CurrentThread.Culture contains your client culture, and not your server one.

Maupertuis
Can I create a resource file with message titles, and using resource manager connect them in the right place?
Sapphire
Yes, see my message, it's event easier than that. ^_^ (beware your resource class autogenerated namespace however. It's computer as other automated class file generations, according to the default project namespace and resource file directory.
Maupertuis
+1  A: 

See the following MSDN article for a detailed tutorial on how to do globalization correctly in ASP.NET:

Noon Silk