Monday, February 4, 2013

Creating SharePoint 2010 Calculated Field from code in sites with different regional settings

Say you need to create the following calculated column in different sites that have different regional settings: English, French, etc. to format the DateTime [Start Time] filed to "dd-mm-yyyy".

The following formula would look list this in English - with a comma separator:
=TEXT([Start Time],"dd-mm-yyyy")
Like this in french - with a semicolon separator:
=TEXT([Start Time];"dd-mm-yyyy")
When creating the column from from code  behind to treat this  the SPWeb.Locale.TextInfo.ListSeparator property must be used to get the correct list separator:
SPList spList = SPContext.Current.Web.Lists["List Title"];
string newFieldName = spList.Add("CalculatedField", SPFieldType.Calculated, false);
SPFieldCalculated newField = (SPFieldCalculated)spList.GetField(newFieldName);
newField.Formula = String.Format(@"=TEXT([Start Time]{0} ""dd-mm-yyyy"")", SPContext.Current.Web.Locale.TextInfo.ListSeparator);
newField.Update();
Post a Comment