Localization in custom web controls are needed when we would want to change default text according to some localized language. This allows the developers to create resource satellite assemblies and deploy as a multi-lingual website. In this post, we would look into creating one such localized button whose text is determined based on the language selected.
Create a resource manager –
- We need a resource manager to read from embedded resource. I have named my resources in the FControls project as “SR”, and so
- My resource class would be sr.cs
- My resource text file would be sr.txt
- My resources generated file would be sr.resources
- Code snippet for the sr class,
How to use the resource manager –
- Define your constants in a sr.txt file. In our example, we are going to have a button whose text is localized.
- Create a sr.txt file and add it to the project,
- Then add the text values that you would expose for localizing. In our FButton, I have kept the localizing string as “ButtonText”. Enter that string in the sr.txt file as,
- ButtonText = Click Me!!
Generate the resources file using resgen –
- We need to create a resources file that would enable our resource manager to read the localized strings,
- Enter the following command in your VS2005/VS2008 command prompt,
- resgen sr.txt sr.resources.resources
- This would create a resources file. Include that in your project.
Use the resource value in your control –
- We would be adding a button control whose text is a localized string. Check out the following code snippet,
- Create a default website project.
- Point your output directory of the library project to the website’s bin directory. This would make your website project refresh whenever you make a change in the control library ( just a quick way to check out ).
- Once everything is set, we can use our FLocButton in our webpage,
- Running this sample, would turn up a page with a button and a text saying “Click Me!!”. Since we are rather interested in getting the localized string into the button. We would directly see how to create one such.
- Add a couple of resource files named in any directory as you would wish to,
- We have a “de-DE” and “fr-FR” named resources added up. Inside the resource file just name the resource string id and its corresponding value that you would want to show up when the UICulture is set. Shown below is a resource string set for “German / de-DE” culture.
Code to localize –
- To set the UICulture use the following code,
- We need to override the InitializeCulture() function in the Page to set the UICulture for the page. In our application, it has a DropDownList, through which we would want the UICulture to set on each postback,
- If you execute the page, the results would be as follows,
- The zipped version of the sample can be found here.
That’s it!!, we have the strings localized.