TOC

The community is working on translating this tutorial into Russian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Localization:

Localizing the CodeBehind

In the previous chapters, we only used localization for the markup part of the webpage, but localizing your strings in Code Behind is just as simple. Here are the techniques for doing this, with some sample code to get you started.

Direct access

Since the .NET framework takes your global resource files and turns them into strongly typed classes, you can actually reference them as such. For instance, if you have a global resource file called MyGlobalResources.resx, with a resource row with a name of HelloWorldString, you can access it like this:

lblHelloWorld.Text = Resources.MyGlobalResources.HelloWorldString;

GetLocalResourceObject()

With a call to GetLocalResourceObject(), you can get a specific row from your local resource file. It is returned as an object, but you can always call the ToString() method on it. For this to work, you have to be within a file that has a local resource file. To get a row from it, simply specify the name of the row as a parameter to the method, like this:

lblHelloWorld.Text = GetLocalResourceObject("lblHelloWorld.Text").ToString();

GetGlobalResourceObject()

The GetGlobalResourceObject() method works pretty much like the local version described above, but for global resources instead. You have to specify an extra parameter though, to tell ASP.NET in which global resource file you want to look for the row in, so the first parameter is the name of the resource class generated from the resource file, while the secondary parameter is for specifying the name of the row you're looking for, like this:

lblHelloWorld.Text = GetGlobalResourceObject("MyGlobalResources", "HelloWorldString").ToString();

Which approach to use mostly depends on the situation and what you prefer, but the first one does have a big advantage: Since it's strongly typed, the compiler will alert you if the row you are trying to retrieve no longer exists, allowing you to catch any problems before they go into production.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!