SharePoint - Client Side Object Model(CSOM) - Managed - Update Item in an Existing List

Problem Definition

Update Item data in an Existing List using Managed Code and Client Side Object Model(CSOM) for SharePoint 2013.

Prerequisites

Code Example


/// <summary>
/// Update Item with data to list
/// </summary>
/// <param name="title"></param>
/// <param name="itemssWithFieldValuePairs">Pass a Comma Separated combination of field title and Value and separate the combo with a semicolon
/// Eg: "Title,Test Entry;FirstName,TestFName1;LastName,TestLName1"
/// </param>
public static void UpdateItemToList(string title, string itemssWithFieldValuePairs)
{
            try
            {
                //var spContext = new ClientContext("http://<your server>/<site>/");
                using (spContext)
                {
                    // Client side SP Web Conext
                    var web = spContext.Web;
                    // Define Exception scope for the site context.
                    var exScope = new ExceptionHandlingScope(spContext);
                    // Get list by its title
                    List list = web.Lists.GetByTitle(title);
                    //New caml query; I have added 2 same records to the list. Following query will pick 1 and update it
                    var query = new CamlQuery();
                    query.ViewXml = "<View><RowLimit>1</RowLimit></View>";
                    var items = list.GetItems(query);
                    spContext.Load(items);
                    spContext.ExecuteQuery();
                    // Parse new fields to be updated
                    var fieldsDict = itemssWithFieldValuePairs.Split(';').ToList().ToDictionary(x => x.Split(',')[0].Trim(), x => x.Split(',')[1].Trim());
                    var item = items.FirstOrDefault();
                    // Set up a list item 
                    if (item!=null)
                    {
                        item["Title"] = fieldsDict["Title"];
                        item["FirstName"] = fieldsDict["FirstName"];
                        item["LastName"] = fieldsDict["LastName"];
                        //Update item
                        item.Update();
                    }
                    // Execute the query to finalize your result
                    spContext.ExecuteQuery();
                    Console.WriteLine("Updated Successfully!!!");
                }
            }
            catch (Exception ex)
            {
                // Print error message
                Console.WriteLine(ex.ToString());
            }
}

Code Result

Before update:
After Update:

Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)