Saturday, August 24, 2013

Insert Item in SharePoint list with specific ID

I recently came across with a problem that someone deleted an item from a list and then cleared the recycle bin. Now that item was previously referred in many lists as lookup field, so they all became null referenced lookup and as a result of that, site got crashed.

So I had 3 choices to correct this :
1) To correct all references in all lists by building a utility or do it manually (time consuming process)
2) To correct the code to handle these type of issues (time consuming process)
3) To insert the item with that specific id.

I tried to find the solution to 3rd option, but had no luck. So, I dig little deeper and came up with this solution. Although it is not a very good idea to set internal fields of sharepoint explicitly. But sometimes we have to do it. :)

Here is the solution :

private static void InsertItemWithSpecificID(int itemID)
{
    string siteUrl = "http://www.contoso.com";
    string listName = "Employee";
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {    
        using (SPSite site = new SPSite(siteUrl))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPList list = web.Lists.TryGetList(listName);

                if (list != null)
                {
                    // The ID field is readonly field, set to to read and write mode.
                    list.Fields[SPBuiltInFieldId.ID].ReadOnlyField = false;
                    list.Update();

                    SPListItem item = list.AddItem();
                    item["Title"] = "This item Id's is not auto-generated by SharePoint, it is specified explicitly.";
                    item[SPBuiltInFieldId.ID] = itemID; //item[SPBuiltInFieldId.ID] = 3;
                    item.Update();
                    list.Fields[SPBuiltInFieldId.ID].ReadOnlyField = true;
                    list.Update();
                }
            }
        }
    });
}