Updating Field Value in SharePoint Using Client-Object Model
Asked Answered
T

4

7

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!

Taraxacum answered 4/8, 2011 at 19:32 Comment(0)
L
16

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().

Lubber answered 5/8, 2011 at 9:20 Comment(6)
Wow, I definitely think this has me on the right track. I have my code updated in my original post, but I am stuck on what to write in my if-statement when I encounter the image I want. Using your example, it seems it's not like items.File["Title"]. Any thoughts?Taraxacum
Nvm, I was able to figure it out. This was still very helpful. Thank you so much!Taraxacum
Sorry, I wasn't on the wire. Nice to see you figured it out yourself. I was pleased to help you ;)Lubber
Thanks for this. Just to let you know I used this code snippet over on SPOverflow: sharepoint.stackexchange.com/questions/22229/…Thuythuya
Hi jumbo, could you give us the example to update field in document library?Anatomist
@WillYu There should be no difference, you can use this code for list and doclib as well.Lubber
L
3

Just remember that every field has an internal name. When you query the field value use indexer, you should give it the internal name, not the one we see in the SharePoint Online.

For example, you add a column named Phone, You should query the value like this:

//query the internal name of the "Phone" field
Field field = list.Fields.GetByInternalNameOrTitle("Phone");
context.Load(field);
context.ExecuteQuery();

//load items
var items = list.GetItems(new CamlQuery());
context.Load(items);
context.ExecuteQuery();

foreach (var item in items)
{
   //here we use the internal name
   Console.WriteLine("\t field, phone:{0}", item[field.InternalName]);
}
Lecythus answered 6/8, 2014 at 8:36 Comment(0)
E
1

The FieldCollection describes the schema of the list items. You need to load actual list items to access their values!

Check out this detailed walkthrough on MSDN for more background on SharePoint and the Client Object Model: http://msdn.microsoft.com/en-us/library/ee857094.aspx#SP2010ClientOM_The_Managed_Client_Object_Model

So in this case the following sample code from the above MSDN page illustrates it:

using System;
using Microsoft.SharePoint.Client;

class Program
{
    static void Main()
    {
        ClientContext clientContext = new ClientContext("http://intranet.contoso.com");
        List list = clientContext.Web.Lists.GetByTitle("Announcements");
        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = "<View/>";
        ListItemCollection listItems = list.GetItems(camlQuery);
        clientContext.Load(list);clientContext.Load(listItems);
        clientContext.ExecuteQuery();
        foreach (ListItem listItem in listItems)
            Console.WriteLine("Id: {0} Title: {1}", listItem.Id, oListItem["Title"]);
    }
}

In particular the value of a list item filed is retrieved as follows:

string itemTitle = oListItem["Title"];

It uses .NET indexer syntax.

Equalize answered 4/8, 2011 at 19:49 Comment(2)
That isn't the entirety of the code, I have loaded the list items. I just need to know how to access the field values. EDIT: I also included some more of my code in the original post.Taraxacum
The way I am looking at that, if my list is "Site Images", is that not just returning all the images in the picture library, not the individual fields within each picture?Taraxacum
T
0

Hope this helps someone out down the road. Thanks everyone for your input!

private static void updateFields()
        {
            //Loads the site list
            clientContext.Load(list);
            //Creates a ListItemCollection object from list
            ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
            //Loads the listItems
            clientContext.Load(listItems);
            //Executes the previous queries on the server
            clientContext.ExecuteQuery();

            //For each listItem...
            foreach (var listItem in listItems)
            {
                //Writes out the item ID and Title
                Console.WriteLine("Id: {0} Title: {1}", listItem.Id, listItem["Title"]);
                //Loads the files from the listItem
                clientContext.Load(listItem.File);
                //Executes the previous query
                clientContext.ExecuteQuery();
                //Writes out the listItem File Name
                Console.WriteLine("listItem File Name: {0}", listItem.File.Name);

                //Looks for the most recently uploaded file, if found...
                if (listItem.File.Name.Contains("Sunset"))
                {
                    //Changes the Title field value
                    listItem["Title"] = title;
                    //Changes the Keywords field value
                    listItem["Keywords"] = keywords1 + keywords2 + keywords3;
                    //Writes out the item ID, Title, and Keywords
                    Console.WriteLine("Id: {0} Title: {1} Keywords: {2}", listItem.Id, listItem["Title"], listItem["Keywords"]);
                }
                //Remember changes...
                listItem.Update();
            }
            //Executes the previous query and ensures changes are committed to the server
            clientContext.ExecuteQuery();
        }
Taraxacum answered 5/8, 2011 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.