2

I'm trying to create items in a list and set the ID field programmatically (for use in a lookupfield in another list). This works serverside by setting the property ReadOnlyField of the field ID to false while inserting.

Code:

private static void InsertItemWithID(int itemID) {
using (SPSite site = new SPSite(siteUrl)) {
    using (SPWeb web = site.OpenWeb()) {
        SPList list = web.Lists.TryGetList(listName);
        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 explicitly specified";
        item[SPBuiltInFieldId.ID] = itemID;
        item.Update();
        list.Fields[SPBuiltInFieldId.ID].ReadOnlyField = true;
        list.Update();
    }
}

}

Now i'm trying to get this to work with the client object model - without success. Instead i'm getting the error message "This field cannot be updated.".

Here's my code:

private static void InsertItemWithSpecificIDCO(int itemID) {
ClientContext context = new ClientContext(siteUrl);
List list = context.Web.Lists.GetByTitle(listName);

var fields = list.Fields;
context.Load(fields);
context.ExecuteQuery();

var field = fields.GetByInternalNameOrTitle("ID");
field.ReadOnlyField = false;
field.Update();
context.Load(field);
context.ExecuteQuery();

ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = list.AddItem(itemCreateInfo);

newItem["ID"] = itemID;
newItem["Title"] = "This item Id's is not auto-generated by SharePoint, it explicitly specified (Client Object Model)";
newItem.Update();
context.ExecuteQuery();  
}

`

Does anybody has a clue whats going wrong?

  • 1
    You are trying to hijack the ID field and use it for something it wasn't intended for. Mucking with it might have all sorts of subtle negative implications for your environment. You're much better off creating a new field and using that. – Derek Gusoff Feb 13 '15 at 21:01
  • So whats the answer? I have the same requirement. I'm writing code to migrate Lists from one site to another and some fields are lookups pointing to ids of another. Its critical that the ids are the same when they are migrated over, and the source list has had a few items deleted, so their IDs are not in perfect order. (sorry i don't have enough rep to comment) – Ryano Jun 7 '17 at 0:53
  • I don't have an answer on the client-side model, but I'm fascinated by the fact that the server-side way works (except the collisions between auto-numbered ID values and the self-assigned ones)! Thank you for this StackOverflow entry. – naivists Jan 3 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.