Programmatically create calculated field in SharePoint 2010

I have a custom list named “Custom”. I need to create a calculated field to this list using SharePoint Object Model.

In this blog we will see how to create calculated field in the custom list using SharePoint Object Model.

Code Snippet:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.SharePoint;

using System.Collections;

 

namespace CalculatedField

{

    class Program

    {

        static void Main(string[] args)

        {

            using (SPSite site = new SPSite("http://serverName/sites/Vijai/"))

            {

                using (SPWeb web = site.OpenWeb())

                {

                    SPList list = web.Lists.TryGetList("Custom");

                    if (list != null)

                    {

                        ////Create a calculated field

                        string calculatedColumn = list.Fields.Add("CalculatedColumn", SPFieldType.Calculated, false);

                        ////Get the newly created calculated field

                        SPFieldCalculated calculatedField = list.Fields[calculatedColumn] as SPFieldCalculated;

                        ////Set the calculated field formula

                        calculatedField.Formula = "=[Title]";

                        ////Set the data type returned from this formula

                        calculatedField.OutputType = SPFieldType.Text;

                        ////Update the calculated field

                        calculatedField.Update();

                    }

                }

            }

        }

    }

}



Calculated Field created successfully:



CalculatedField.png