Goal
Our site is created using variations in both English and Spanish. Create a Visual Web Part which can use the resource file(.resx) to show different texts for different language.
Steps to achieve goal
- Create a SharePoint project with name "Sample".
- Add a web part with name "SampleWebPart".
- Add a "Mapped Folder" to "Resources". 2 files needs to be added.
- SampleWebPart.en-US.resx - English version resource file. Add some text to the resource.
- SampleWebPart.es-ES.resx - Spanish version resource file. Add some text to the resource.
- At this point the project "Solution Explorer" will look like
- For applying the resource, Open the Feature1 properties. And make the 2 changes shown in the below given image.
- Use the HTML and C# Code below.
- Once the above given steps are done, deploy the web part and They will display as below given image.
HTML - SampleWebPartUserControl.ascx
<h1><asp:Literal ID="ltrlTitle" runat="server" /></h1>
<hr />
<h3>
<asp:Literal ID="ltrlDescription" runat="server" />
</h3>
C# - SampleWebPartUserControl.ascx.cs
#region System
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
#endregion
namespace Sample.SampleWebPart
{
/// <summary>
/// Simple example to use Resouce file with English/Spanish language.
/// </summary>
public partial class SampleWebPartUserControl : UserControl
{
#region Events
/// <summary>
/// Page Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
ltrlTitle.Text = LoadResource( ResourceName.Title );
ltrlDescription.Text = LoadResource(ResourceName.Description);
}
#endregion
#region Resource Reader
/// <summary>
/// Name for the Version to be considered.
/// NOTE :- Use exactly same "Name" as used in Resource(resx) file.
/// </summary>
public enum ResourceName
{
Title,
Description
}
/// <summary>
/// Gets the text on the basis of "Name" in Resource(resx).
/// </summary>
private string LoadResource(ResourceName _resName)
{
return Microsoft.SharePoint.Utilities.SPUtility.GetLocalizedString("$Resources:" + _resName.ToString(),
"SampleWebPart"
, (uint)System.Globalization.CultureInfo.CurrentUICulture.LCID);
}
#endregion
}
}
Happy Coding