Wednesday, December 3, 2008

Globalization and Localization in C#.net

Take one Drop down list
Take four labels and text boxes
Take global, local Resources file from solution explorer right click add the parameter values to it
Implement this code and enjoy........


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;
using System.Resources;
using System.Reflection;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//CultureInfo Class GetCultures gives collection of language.
lblWelcome.Text = Resources.Resource.lblWelcome ;
lblWelcome.ForeColor = Color.FromName(Resources.Resource.lblWelcome);
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
//Filling the language collection into drop-downlistbox for user choice.
ddl_SelectLanguage.Items.Add(new ListItem(ci.EnglishName, ci.Name));
}
//Calling the Event when page loads for the first time.
ddl_SelectLanguage_SelectedIndexChanged(sender, e);
}
}
protected void ddl_SelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddl_SelectLanguage.SelectedValue);
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddl_SelectLanguage.SelectedValue);
//Applying Localization
ApplyLocalization();
ApplyUILocalization();

}


private void ApplyUILocalization()
{

lblLanguageName.Text = Convert.ToString(this.GetLocalResourceObject("LanguageName"));
lblLongDate.Text = Convert.ToString(this.GetLocalResourceObject("LongDate"));
lblCurrency.Text = Convert.ToString(this.GetLocalResourceObject("Currency"));
lblAmount.Text = Convert.ToString(this.GetLocalResourceObject("amt"));

}


private void ApplyLocalization()
{
//Lets Assume currency and amount to keep example simple.
double dblCurrency = 500.50;
double dblAmount = 9580000.75;


//No extra effort for localization as you see here.
txtLangName.Text = ddl_SelectLanguage.SelectedItem.Text;
txtLongDate.Text = DateTime.Now.ToLongDateString();
txtCurrency.Text = dblCurrency.ToString("c");
txtAmount.Text = dblAmount.ToString("n");

}

}

No comments: