Tuesday, August 5, 2014

SharePoint 2013 - Update list items with client object model

Here is a very simple example of using SharePoint Client Object Model. In this example I will update every item in my list, i.e. I will update field "Address" with value "my new value". 

1. Open Visual Studio and go to File --> New Project
2. Select Windows --> Console Application (or SharePoint Console Application)
3. Add Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime references to your project:



4. Paste this code in you new project:




using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {

            // Here you need to enter url of your site
            ClientContext ctx = new ClientContext("http://yourSiteUrl");

            // Get the list by its name - here you enter your list title
            List list = ctx.Web.Lists.GetByTitle("ListTitle");

            ListItemCollection coll = list.GetItems(CamlQuery.CreateAllItemsQuery());
            // we need to load all fields
            ctx.Load(coll);
            ctx.ExecuteQuery();

            // change value of one field in every list item
     // NOTE: this field must exist in your list
            foreach (var item in coll) {
                item["Address"] = "my new value";
                item.Update();
                ctx.ExecuteQuery();               
            }
        }
    }
}

No comments:

Post a Comment