Archive for May, 2011

05/06/11
Fahad Zia
tags:  

SharePoint list ID column in a calculated column does not update


To show what I am talking about, create a custom list and add a calculated column called “Print ID” with the formula “=ID”. Add a new record with Title as Test and you will see something similar to below:

id1

The “Print ID” column displays 0 although if you hover over the title “Test” you see ID=1. This happens because when the item is added it did not have the ID generated in the database yet. So to update this column, go to the “Print ID” calculated column of the list, edit it and press OK which recalculates the formula and shows the correct value of ID as shown below.

id2

Unfortunately it does not end there as if you edit this item the “Print ID” column again resets to 0 which means you will have to ONCE AGAIN update the calculated column. With the knowledge that the calculated column needs to be updated after the item is added and after the item is modified, we can create an event handler that automates this for us. Here is the solution I used:

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

namespace NCR
{
    class NCRListEventHandler: SPItemEventReceiver
    {
        /// <summary>
        /// Update NCRPrint calculated column so ID column is not blank. Without this new items have ID empty in NCRPrint column
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            UpdateNCRPrintField(properties);
        }

        /// <summary>
        /// Without this the ID in the calculated column after update becomes 0 or empty
        /// </summary>
        /// <param name="properties"></param>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            UpdateNCRPrintField(properties);            
        }

        private void UpdateNCRPrintField(SPItemEventProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(properties.SiteId))
                {
                    using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
                    {
                        SPField fldNCRPrint = web.Lists.GetList(properties.ListId, false).Fields.GetFieldByInternalName(Helper.FieldNames.NCRPrint.ToString());
                        fldNCRPrint.Update(true);
                    }
                }
            });   
        }
    }
}