The better way to do this, is through ProcessBatchData. In this we construct a CAML string contains a batch of commands to perform the updates. Then we should execute the commands by using the ProcessBatchData command of an SPWeb object.
Each command includes a Method element with SetVar subelements.
The SetVar elements define
- Type of command e.g. <SetVar Name=\"Cmd\">
- ID of the item e.g. <SetVar Name=\"ID\">
- Fields to update. The fields are defined in the format
<schema>#<internal_field_name> e.g.
<SetVar Name=\"urn:schemas-microsoft-com:office:office#PersonID\">
The Guid of the List must be specified in <SetList> tag.
After all the commands are created, they are placed in an ows:Batch element. This element contains an OnError attribute that defines what happens if an exception occurs while the commands are executed
Thats it, here is the snippet
Batch command to add a new item to Sharepoint list
As we are going to add a new item, just specify "New" in place of ID <SetVar Name \"ID\">. I have highlighted in the below code snippet.
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
string listGuid = list.ID.ToString();
string _xmlData = "";
SPUser theUser = web.SiteUsers[_userID];
SPListItem item = list.Items.Add();
string _personID = theUser.ID.ToString() + ";#" + theUser.Name;
batch = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ows:Batch OnError=\"Return\">{0}</ows:Batch>" + "<Method ID=\"{0}\">" +
"<SetList>" + listGuid + "</SetList>" +
"<SetVar Name=\"Cmd\">Save</SetVar>" +
"<SetVar Name=\"ID\">New</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#PersonID\">" + _personID + "</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#XmlData\">" + _xmlData + "</SetVar>" +
"</Method>";
string batchReturn = web.ProcessBatchData(batch);
}
}
Batch command to update an item in the Sharepoint list
To update an item in the sharepoint list, we just need to put the item id to update in the tag <SetVar Name \"ID\">. I have highlighted in the below code snippet.
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["ListName"];
string listGuid = list.ID.ToString();
string _xmlData = "";
SPUser theUser = web.SiteUsers[_userID];
SPListItem item = list.Items.Add();
string _personID = theUser.ID.ToString() + ";#" + theUser.Name;
batch = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ows:Batch OnError=\"Return\">{0}</ows:Batch>" + "<Method ID=\"{0}\">" +
"<SetList>" + listGuid + "</SetList>" +
"<SetVar Name=\"Cmd\">Save</SetVar>" +
"<SetVar Name=\"ID\">ItemID</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#PersonID\">" + _personID + "</SetVar>" +
"<SetVar Name=\"urn:schemas-microsoft-com:office:office#XmlData\">" + _xmlData + "</SetVar>" +
"</Method>";
string batchReturn = web.ProcessBatchData(batch);
}
}