SharePoint  

Calculated Field in SharePoint 2010 Programmatically Using VS 2012


Introduction

Today, in this article let's play around with one of the interesting and most useful concepts in SharePoint 2010.

Question: What is a calculated field?
 

In simple terms "You can have any type of numeric calculations for any field in a list or to perform any string data manipulations".

Step 1: Open SharePoint 2010 Central Administration and navigate to a specific site.

 

Step 2: Open up Visual Studio 2012 and try to create a "SharePoint Visual Web Part" project, as in:

 

open-sharepoint2010-visual-webpart.jpg
 

Step 3: Select "Deploy as a farm solution" as in the following and click the "Finish" button.

 

sharepoint-customization-wizard.jpg
 

 Step 4: The complete code of visualwebpart1usercontrol.ascx looks like this:

 

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>

<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"

    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"

    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@  Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1.ascx.cs"

    Inherits="CalculatedFieldProgramaticallyApp.VisualWebPart1.VisualWebPart1" %>

<div style="text-align: center;">

    <table>

        <tr>

            <td colspan="2">

                <asp:label id="Label1" runat="server" text="Calculated Column in SharePoint 2010 using VS 2012"

                    font-bold="true" font-size="Large" font-names="Verdana" forecolor="Maroon"></asp:label>

            </td>

        </tr>

        <tr>

            <td>

                <asp:label id="Label2" runat="server" text="Please Enter List Name" font-size="Large"

                    font-names="Verdana" font-italic="true"></asp:label>

            </td>

            <td>

                <asp:textbox id="TextBox1" runat="server"></asp:textbox>

            </td>

        </tr>

        <tr>

            <td>

                <asp:label id="Label3" runat="server" text="Please Enter Calculated Field Name" font-size="Large"

                    font-names="Verdana" font-italic="true"></asp:label>

            </td>

            <td>

                <asp:textbox id="TextBox2" runat="server"></asp:textbox>

            </td>

        </tr>

        <tr>

            <td>

                <asp:label id="Label4" runat="server" text="Please Enter Calculated Field Formula"

                    font-size="Large" font-names="Verdana" font-italic="true"></asp:label>

            </td>

            <td>

                <asp:textbox id="TextBox3" runat="server"></asp:textbox>

            </td>

        </tr>

        <tr>

            <td colspan="2">

                <asp:button id="Button2" runat="server" text="Create List Fields" font-names="Verdana"

                    width="166px" backcolor="Orange" font-bold="True" onclick="Button2_Click" />

            </td>

        </tr>

        <tr>

            <td colspan="2">

                <asp:label id="Label5" runat="server" font-bold="true" font-names="Verdana" forecolor="Maroon"></asp:label>

            </td>

        </tr>

    </table>

</div>
 

Step 5: The complete code of visualwebpart1usercontrol.ascx.cs looks like this:

 

using Microsoft.SharePoint;

using System;

using System.ComponentModel;

using System.Web.UI.WebControls.WebParts;namespace CalculatedFieldProgramaticallyApp.VisualWebPart1

{

    [ToolboxItemAttribute(false)]

    public partial class VisualWebPart1 : WebPart

    {

        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling using

        // the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready

        // for production. Because the SecurityPermission attribute bypasses the security check for callers of

        // your constructor, it's not recommended for production purposes.

        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]

        public VisualWebPart1()

        {

        }

        protected override void OnInit(EventArgs e)

        {

            base.OnInit(e);

            InitializeControl();

        }

        protected void Page_Load(object sender, EventArgs e)

        {

            TextBox1.Focus();

        }

        protected void Button2_Click(object sender, EventArgs e)

        {

            if (string.IsNullOrEmpty(TextBox1.Text) || string.IsNullOrEmpty(TextBox2.Text))

            {

                Label5.Text = "Please Enter Some Values";

                Label5.ForeColor = System.Drawing.Color.Red;

            }

            else

            {

                SPWeb web = SPContext.Current.Web;

                SPList list = web.Lists[TextBox1.Text];

                SPFieldCalculated calc = (SPFieldCalculated)list.Fields.GetFieldByInternalName(list.Fields.Add(TextBox2.Text, SPFieldType.Calculated, true));

                calc.Formula = TextBox3.Text;calc.Currency = SPCurrencyFieldFormats.UnitedStates;calc.Update();

                SPView view = list.DefaultView;

                view.ViewFields.Add(TextBox2.Text);

                view.Update();

                Label5.Text = TextBox2.Text + " - Field Successfully Created";

                Label5.ForeColor = System.Drawing.Color.Green;

                TextBox1.Text = string.Empty;

                TextBox2.Text = string.Empty;

                TextBox3.Text = string.Empty;

            }

        }

    }

}

 

Step 6: Deploy the solution file and add the new webpart to a SharePoint site.

 

Step 7: The output of the application looks like this:

 

calculated-column-in-sharepoint2010.jpg
 

 

Step 8: Entering calculated field data output of the application looks like this:

 

app-calculated-column-in-sharepoint2010.jpg
 

 

Step 9: Item adding to the list output of the application looks like this:

 
  Item-adding-to-the-list-sharepoint2010.jpg

 

Step 10: Item added to the list output of the application looks like this:

 

Item-added-to-the-list-sharepoint2010.jpg
 

I hope this article is useful for you.

MVC Corporation is consulting and IT services based company.