Search code examples
sharepointsharepoint-2016

SharePoint - programmatically add list items can't set ID


I need to create new list item in sharepoint 2016 but while creating, on ID field, i'm getting this error: "This field cannot be updated". I'm not updating anything and i checked the list and it was empty too. I left this field empty and it has 0 value by defualt like when i'm inserting new row in sql tables.


Solution

  • The ID field is a system field which will increase automatically when new item created, so no need to set ID field value, here is a code snippet which add new item with default Title field and ID field will be automatically generated with 1 as it is a empty list previously:

                SPSite site = new SPSite("http://demoaam.contoso2016.com/sites/dev");
                using (SPWeb web=site.OpenWeb() )
                {
                    SPList list = web.Lists["TestList"];
                    SPListItem newitem = list.AddItem();
                    newitem["Title"] = "NewItemTitle";
                    newitem.Update();
    
                }
    

    enter image description here