SharePoint List WebService to Insert Item

Using the SharePoint List WebService to insert an item into a list...

WebService Reference: http://<servername>/_vti_bin/Lists.asmx

try
{
 ws_list.Lists list = new ws_list.Lists();
 list.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
 XmlDocument doc = new XmlDocument();
 XmlElement batch_element = doc.CreateElement("Batch");
 string item = "<Method ID=\"1\" Cmd=\"New\">" + "<Field Name=\"ID\">New</Field>" + "<Field Name=\"Title\">This is a test</Field>" + "</Method>";
 batch_element.InnerXml = item;
 list.UpdateListItems("ListTest", batch_element);
}
catch(Exception ex)
{
string err = ex.Message;
}
 

Another Example

            try
            {

                /*Declare and initialize a variable for the Lists Web service.*/
                siteWebServiceLists.Lists listService = new siteWebServiceLists.Lists();

                /*Authenticate the current user by passing their default credentials to the Web service from the system credential cache.*/
                listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                listService.Url = url + "/_vti_bin/Lists.asmx";
                System.Xml.XmlNode ndListView = listService.GetListAndView(list, "");
               
                /*Create an XmlDocument object and construct a Batch element and its attributes. Note that an empty ViewName parameter causes the method to use the default view. */
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
               
                batchElement.SetAttribute("OnError", "Continue");
                batchElement.SetAttribute("ListVersion", "1");
                batchElement.InnerXml = "<Method ID='1' Cmd='New'>" +
                "<Field Name='Title'>Title</Field>" +
                "<Field Name='First_x0020_Name'>Wayne</Field>" +
                "<Field Name='Last_x0020_Name'>Magnum</Field>" +
                "</Method>";

                /*Update list items. This example uses the list GUID, which is recommended, but the list display name will also work.*/
                System.Xml.XmlNode n = listService.UpdateListItems(list, batchElement);
                XmlTextReader xr = new XmlTextReader(n.OuterXml, XmlNodeType.Element, null);
                while (xr.Read())
                {
                    if (xr.ReadToFollowing("z:row"))
                    {
                        if (xr["ows_ID"] != null)
                        {
                            Console.WriteLine(xr["ows_ID"].ToString());
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

Print | posted @ Thursday, March 27, 2008 12:58 AM

Comments on this entry:

Gravatar # re: SharePoint List WebService to Insert Item
by Ryan at 11/4/2008 3:42 PM

My code doesn't throw an error or perform an insert. Do you have any ideas about what could be causing this problem?

private void button1_Click(object sender, EventArgs e)
{
try
{
//get data from form
string ContactName = textBox1.Text;
string PhoneNumber = textBox2.Text;
string Website = textBox3.Text;
string SecretIdentity = textBox4.Text;

// Declare and initialize a variable for the Lists Web Service.
sitesWebServiceLists.Lists listService = new sitesWebServiceLists.Lists();

/* Authenticate the current user by passing their default
credentials to the Web Service from the system credential cache.*/
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

XmlDocument x_doc = new XmlDocument();
XmlElement xe_batch = x_doc.CreateElement("Batch");

string sb_method = "<Method ID=\"1\" Cmd=\"New\">" + "<Field Name=\"ID\">New</Field>" + "<Field Name=\"Contact_x0020_Name\">" + ContactName + "</Field>" + "<Field Name=\"Phone_x0020_Number\">" + PhoneNumber + "</Field>" + "<Field Name=\"Website\">" + Website + "</Field>" + "<Field Name=\"Secret_x0020_Identity\">" + SecretIdentity + "</Field>" + "</Method>";

MessageBox.Show(sb_method);

xe_batch.InnerXml = sb_method;
listService.UpdateListItems("{D8235ED3-BD7D-499F-8AFC-37877E34ADA7}", xe_batch);
}
catch(Exception ex)
{
string err = ex.Message;
}
}
Gravatar # re: SharePoint List WebService to Insert Item
by Ryan at 11/6/2008 1:38 PM

I found the answer after a few days of searching. The main problem is that no matter what list you are updating you must put Title as the first column name rather than the actual column name. Here is the code I ended up with that did work.

//get data from form
string ContactName = textBox1.Text;
string PhoneNumber = textBox2.Text;
string Website = textBox3.Text;
string SecretIdentity = textBox4.Text;

// Declare and initialize a variable for the Lists Web Service.
sitesWebServiceLists.Lists listService = new sitesWebServiceLists.Lists();

/* Authenticate the current user by passing their default
credentials to the Web Service from the system credential cache.*/
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

/*Set the Url property of the service for the path to a subsite.*/
listService.Url = "http://brnet/it/playground/_vti_bin/Lists.asmx";

/*Get Name attribute values (GUIDs) for list and view. */
System.Xml.XmlNode ndListView = listService.GetListAndView("Test List", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

/*Create an XmlDocument object and construct a Batch element and its attributes. Note that an empty ViewName parameter causes the method to use the default view. */
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");
batchElement.SetAttribute("ViewName", strViewID);

batchElement.InnerXml = "<Method ID='1' Cmd='New'><Field Name='Title'>" + ContactName + "</Field><Field Name='Phone_x0020_Number'>" + PhoneNumber + "</Field><Field Name='Website'>" + Website + "</Field><Field Name='Company'>" + SecretIdentity + "</Field></Method>"; //"<Method ID=\"1\" Cmd=\"New\">" + "<Field Name=\"ID\">New</Field>" + "<Field Name=\"Contact_x0020_Name\">" + ContactName + "</Field>" + "<Field Name=\"Phone_x0020_Number\">" + PhoneNumber + "</Field>" + "<Field Name=\"Website\">" + Website + "</Field>" + "<Field Name=\"Secret_x0020_Identity\">" + SecretIdentity + "</Field>" + "</Method>";

//MessageBox.Show(sb_method);

/*Update list items. This example uses the list GUID, which is recommended, but the list display name will also work.*/
try
{
XmlNode ndReturn = listService.UpdateListItems(strListID, batchElement);

//show return from insert
MessageBox.Show(ndReturn.OuterXml);

//parse the xml to grab the id element needed
string ReturnID = "";
XmlNode resultNode = ndReturn.FirstChild;

foreach (XmlNode childNode in resultNode.ChildNodes)
{
foreach (XmlAttribute attrib in childNode.Attributes)
{
if (attrib.Name == "ows_ID")
{
ReturnID = attrib.Value.ToString();
}
}
}

//show return id
MessageBox.Show(ReturnID);
}
catch (SoapServerException ex)
{
MessageBox.Show(ex.Message);
}
Gravatar # re: SharePoint List WebService to Insert Item
by vishnu at 12/16/2008 3:28 AM

hi,

I am Coldfusion , have been assignemnd with some sharepoint work .

I want to add an item in announcemt list , can anyone give me sample code to insert an item in announcment list (which will have aexpiry date
)
Gravatar # re: SharePoint List WebService to Insert Item
by Wayne Magnum at 1/28/2009 7:10 PM

If your using the MOSS API's the link below gives a good example on how to accomplish this...

Sample Code
string strDashListRoot = "http://spSite/SubSite/Lists/MyList/";
using(SPSite site = new SPSite(strDashListRoot))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyList"];
SPListItem Item = list.Items.Add();
item["Title"] = txtCompanyName.Text;
item["DateReceived"] = System.DateTime.Now;
item["Description"] = txtDescription.Text;
//Important: Comma and space required to add the description
item["EnquiryDetail"] = "http://spSite/SubSite/ListProcess/Assign.aspx?EnquiryID=" + m_iEnquiryId + ", " + txtCompanyName.Text;
item.Update();
iListItemId = item.ID;
}
}

Source...
http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html

Gravatar # re: SharePoint List WebService to Insert Item
by Abul at 1/29/2009 9:01 AM

Hi
Thanks for your quick response. actually i am not using moss. how can i accomplish this without MOSS. again i am really appreciate your help.

Gravatar # re: SharePoint List WebService to Insert Item
by Wayne Magnum at 1/29/2009 11:00 PM

How are you inserting the data into the SharePoint list? Can you send me a snippet of your code?
Gravatar # re: SharePoint List WebService to Insert Item
by Abul at 1/30/2009 8:30 AM

Here is my code snippet:
ListService.Lists list = new ListService.Lists();
list.Credentials = new System.Net.NetworkCredential(txtUserID.Text, txtPassword.Text, txtDomain.Text);
list.Url = "http://mainSite/Subsite/class/_vti_bin/Lists.asmx";
XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");
string strBatch = "<Method ID='1' Cmd='New'>" +
"<Field Name='ID'>New</Field>" + "<Field Name='FName'>" + TextBox1.Text + "</Field>" +
"<Field Name='LName'>" + TextBox2.Text + "</Field>" + "</Method>";
elBatch.InnerXml = strBatch;
XmlNode ndReturn = list.UpdateListItems("Book", elBatch);
lblError.Text = "Successfully added in sharepoint";
Gravatar # re: SharePoint List WebService to Insert Item
by Wayne Magnum at 2/1/2009 7:44 PM

Add this in your code between your ndReturn and LlblError.Text

XmlTextReader xr = new XmlTextReader(ndReturn.OuterXml, XmlNodeType.Element, null);
while (xr.Read())
{
if (xr.ReadToFollowing("z:row"))
{
if (xr["ows_ID"] != null)
{
Create your Hyperlink here
}
}
}


All you have to do now is create your hyperlink once you get the listitem ID.

Let me know how it goes.
-Wayne
Gravatar # re: SharePoint List WebService to Insert Item
by Abul at 2/3/2009 10:56 AM

Hi
Let say for simplicity i have saved FName = Larry and LName = king in sharepoint Name List from AddressBook.aspx. Let say i want to open this FName and LName in my AddressBook.aspx from sharepoint for edit(don't want to edit within sharepoint). how do i create a link and after finished editing data will save back to sharepoint.is it possible?

Thanks.
Gravatar # How to set Save As Dialog to a default location
by Abul at 2/3/2009 12:14 PM

Hi
I have created a Xml file in asp.net and want to save it at
http://mysites.global.com/personal/class/Enrollment/. Under Enrollment we have Tier1, Tier2, Tier3 folder. User can save this xml file any of these three folder. when i open the save as dialog box to save this xml file it always open to my desktop location to save this xml file. how do i set this location in my server folder so that when user want to save this file the save as dialog box will open with this sever location in asp.net.

Thanks.
Gravatar # re: SharePoint List WebService to Insert Item
by sweha at 3/6/2009 12:52 PM

how do you pass a 3/12/2008 which is a value of a textbox txtdate.txt in a webform to a field called DueDate in sharepoint list. DueDate in sharepoint list is a datetime date only type of field. It does not work like it would work for a name or a phone number your example shows.
Gravatar # re: SharePoint List WebService to Insert Item
by Wayne Magnum at 3/11/2009 10:53 AM

You will need to parse txtdate.txt into a Datetime format. Can you send me a snippit of what you have?
Gravatar # re: SharePoint List WebService to Insert Item
by sankar at 5/18/2009 7:49 AM

hi i want to update Created By field in the same way .Is it possible ..?
Gravatar # re: SharePoint List WebService to Insert Item
by Wayne at 5/20/2009 10:48 AM

Never tried that but it should be the same way as well.
Gravatar # re: SharePoint List WebService to Insert Item
by Burhan ERSOY at 9/18/2009 12:07 PM

Hi
i can add items from My Windows Form Applications.
But, how can i add items under the folder on lists.

thanks for advice
Gravatar # re: SharePoint List WebService to Insert Item
by eyan at 11/22/2009 4:54 PM

Hye, thank you for your great post. I have one difficulty though. I can't pass the choice menu to the list. How can I accomplish this.

Thank you in advanced.
Gravatar # re: SharePoint List WebService to Insert Item
by Wayne Magnum at 11/23/2009 10:16 AM

What type of choice menu are you using? Drop Downlist, Rabio Button List, etc?

Let me know.
-Wayne
Gravatar # re: SharePoint List WebService to Insert Item
by Bubba Piersol at 1/20/2010 10:31 AM

I have a Windows Form Application that I am trying to use to insert items into a list. I have followed the code from MSDN and other site (in fact it looks nearly the same as above) but it does not insert an item. Nor does it kick an error. I have made it display the return XML in a message box. It returns this...
<Results xmlns-"http://schemas.microsoft.com/sharepoint/soap/"/>

Here is my code..


Lists.Lists listService = new Lists.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = "SITE/SUB/SUB/_vti_bin/Lists.asmx";
XmlNode ndListView = listService.GetListAndView("Test", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

string strBatch = "<Method ID='1' Cmd='New'>";
strBatch += "<Field Name='Title'>Hello World</Field>";
strBatch += "</Method>";

XmlDocument xmlDoc = new XmlDocument();
XmlElement elBatch = xmlDoc.CreateElement("Batch");

elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ListVersion", "1");
elBatch.SetAttribute("ViewName", strViewID);

elBatch.InnerText = strBatch ;

try
{
XmlNode ndReturn = listService.UpdateListItems(strListID, elBatch);
MessageBox.Show(ndReturn.OuterXml);
}

catch (Exception ex) { MessageBox.Show(ex.Message); }


Any help you can offer would be appreciated.
Gravatar # re: SharePoint List WebService to Insert Item
by NishthaSB at 3/25/2010 1:20 AM

Hi,Have u worked with SharePoint 2010 web services to insert list item by a user with limited access?
Gravatar # re: SharePoint List WebService to Insert Item
by Wayne Magnum at 3/31/2010 7:40 AM

I have not had a chance to working on SharePoint 2010. I will be starting a project which will involve SharePoint 2010.
Gravatar # re: SharePoint List WebService to Insert Item
by carla at 6/11/2010 4:22 PM

I have been tasked with updating a sharepoint list with data from a database using coldfusion via a web service.
No clue where to begin!
Gravatar # re: SharePoint List WebService to Insert Item
by SharepointDeve at 3/20/2011 1:37 AM

I need to add Multi choice value, how I can add that thrugh web service
Gravatar # re: SharePoint List WebService to Insert Item
by shravan at 5/9/2011 11:34 PM

how can i add xml data into sharepoint listcolumn using web services
Gravatar # re: SharePoint List WebService to Insert Item
by Roni at 10/5/2011 3:19 AM

i am trying to use the same method to update an announcements item in my sharepoint server 2007 site
for some reason the following line

batchElement.InnerXml = "<Method ID='1' Cmd='New'>" +
"<Field Name='Title'> " + txtSearch.Text.Trim() + " </Field>" +
"<Field Name='Body'>tt<html><head></head><body>123 12 3123 12312 312</body></html>tt</Field></Method>";

only stores the title and stores tt in the body..

anyway to bypass this?
Gravatar # re: SharePoint List WebService to Insert Item
by Elias at 2/9/2012 11:04 AM

list.Url = url + "/_vti_bin/Lists.asmx";
OR
listService.Url = url + "/_vti_bin/Lists.asmx";

depending the example.

otherwise on SP2010 throws an Exception:

Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: