Introduction
Hi everyone, this is my second article on The Code Project. Like the first one, I expect some feedback from you for this article as well. Thank you in advance!
Here I have worked on the localization concepts that have been introduced in .NET 2.0. But these concepts are nothing new.
Using the Code
I will list the methods with some brief explanation. I am not following Best Practices in Code Design. Since the concepts are not new, I have not explained much.
<asp:DropDownList ID="DropDownList1" runat="server" Width="161px" AutoPostBack="True">
<asp:ListItem Value="en-US">Default</asp:ListItem>
<asp:ListItem Value="ar-AE">Arabic</asp:ListItem>
<asp:ListItem Value="fr-FR">French</asp:ListItem>
<asp:ListItem Value="de-DE">German</asp:ListItem>
<asp:ListItem Value="it-IT">Italian</asp:ListItem>
<asp:ListItem Value="pt-PT">Portuguese</asp:ListItem>
<asp:ListItem Value="ru-RU">Russian</asp:ListItem>
<asp:ListItem Value="el-GR">Greek</asp:ListItem>
<asp:ListItem Value="hi-IN">Hindi</asp:ListItem>
<asp:ListItem Value="ja-JP">Japanese</asp:ListItem>
<asp:ListItem Value="ta-IN">Tamil</asp:ListItem>
</asp:DropDownList>
Here, I have first added 12 languages in the dropdownlist.
Then, I have added a div
in which the text is inserted as ASP literal control.
<asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:Resource, Language%>">
</asp:Literal>:
<asp:Literal ID="Literal2" runat="server"
Text="<%$ Resources:Resource, Language_Name%>">
</asp:Literal>
Below this, I added a Label
in which the text changes when a button is clicked. This is to show how to change the culture on a button click.
The design of the page will be:
Now the code that is written in code behind:
C# provides an overridden method called InitialCulture()
. In this method, we wrote the following code so that whenever the page is loaded, this method is invoked.
protected override void InitializeCulture()
{
string culture = Request["DropDownList1"];
if (culture == null)
{
culture = "en-US";
}
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
}
In the Click event of the button, we write the following code:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = Resources.Resource.Welcome;
}
Output
Points of Interest
The code is very simple and easy to write. Thus we can implement a resource file for any number of cultures.
In my next article, you will see how we can read the resource contents by using Resource file readers and how to edit the resource contents by treating resource files as an XML File.
Conclusion
If you find this article useful, I will appreciate your feedback. Thank you.
Expect more from me SOON!
History
- 5th April, 2007: Initial post