Programmatically set the calculated field formula in SharePoint 2010

I have a custom list named “Employees" which has the following columns.

  • FirstName – Single line of text
  • LastName – Single line of text
  • FullName – Calculated Field

In this blog you will see how to set the calculated field formula using SharePoint Object Model.

Formula for FullName 

 =[LastName]&","&[FirstName] 

Description 

Combines the last name and first name separated by comma (Ramalingam, Vijai).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint; 

namespace CalculatedField
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://shashankpc:2012/sites/test"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Employees");
                    if (list != null)
                    {
                        SPFieldCalculated calculatedField = list.Fields.GetFieldByInternalName("FullName") as SPFieldCalculated;
                        calculatedField.Formula="=[LastName]&\",\"&[FirstName]";
                        calculatedField.Update();
                    }
                }
            }
        }
    }
}