Updating Field Value in SharePoint Using Client-Object Model

This 0ne Pr0grammer picture This 0ne Pr0grammer · Aug 4, 2011 · Viewed 61.2k times · Source

So I am trying to create a method that is essentially used to change the value of a field in SharePoint.

This is what I have so far...

static String fieldName1 = "Title";
static String fieldName2 = "Keywords";
static String title = "A Beautiful Sunset";
static String keywords1 = "test1";
static String keywords2 = "test2";
static String keywords3 = "test3";

static NetworkCredential credentials = new NetworkCredential(username, password, domain);
static ClientContext clientContext = new ClientContext(URL);
static Web site = clientContext.Web;
static List list = site.Lists.GetByTitle(listName);
static FileCreationInformation newFile = new FileCreationInformation();

private static void updateFields()
{
    clientContext.Load(list);
    FieldCollection fields = list.Fields;
    clientContext.Load(fields);
    clientContext.Load(list.RootFolder);

    ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
    clientContext.Load(listItems);
    clientContext.ExecuteQuery();

    foreach (var listItem in listItems)
    {
        Console.WriteLine("Id: {0} Title: {1}", listItem.Id, listItem["Title"]);
        clientContext.Load(listItem.File);
        clientContext.ExecuteQuery();
        Console.WriteLine("listItem File Name: {0}", listItem.File.Name);

        if (listItem.File.Name.Contains("Sunset"))
        {
            ////????????
        }
        listItem.Update();
    }
    clientContext.ExectueQuery();
}

I know how to get to the field, but I am not sure how to access the actual value within the field and modify it. Does anyone have any experience with this using the client-object model? Thank you for any help that's offered!

Answer

jumbo picture jumbo · Aug 5, 2011

Updating of a field with Client Object Model is pretty straight forward:

ClientContext ctx = new ClientContext("http://yoursite");
List list = ctx.Web.Lists.GetByTitle("ListName");
ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(items); // loading all the fields
ctx.ExecuteQuery();

foreach(var item in items)
{
    // important thing is, that here you must have the right type
    // i.e. item["Modified"] is DateTime
    item["fieldName"] = newValue;

    // do whatever changes you want

    item.Update(); // important, rembeber changes
}
ctx.ExecuteQuery(); // important, commit changes to the server

With DocumentLibrary it is quite defferent - you get those same ListItem objects, but to access the associated file you must use item.File property. So ListItem itself will contain field values, listItem.File will contain file, say image.
And don't forget - to access that file you must Load() it and then ExecuteQuery().