Geeks With Blogs
Wayne Magnum's Blog

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;
            }

Posted on Thursday, March 27, 2008 12:58 AM SharePoint 2007 | Back to top


Comments on this post: SharePoint List WebService to Insert Item

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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;
}
}
Left by Ryan on Nov 04, 2008 3:42 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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);
}
Left by Ryan on Nov 06, 2008 1:38 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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
)
Left by vishnu on Dec 16, 2008 3:28 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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

Left by Wayne Magnum on Jan 28, 2009 7:10 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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.

Left by Abul on Jan 29, 2009 9:01 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
How are you inserting the data into the SharePoint list? Can you send me a snippet of your code?
Left by Wayne Magnum on Jan 29, 2009 11:00 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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";
Left by Abul on Jan 30, 2009 8:30 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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
Left by Wayne Magnum on Feb 01, 2009 7:44 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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.
Left by Abul on Feb 03, 2009 10:56 AM

# How to set Save As Dialog to a default location
Requesting Gravatar...
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.
Left by Abul on Feb 03, 2009 12:14 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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.
Left by sweha on Mar 06, 2009 12:52 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
You will need to parse txtdate.txt into a Datetime format. Can you send me a snippit of what you have?
Left by Wayne Magnum on Mar 11, 2009 10:53 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
hi i want to update Created By field in the same way .Is it possible ..?
Left by sankar on May 18, 2009 7:49 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
Never tried that but it should be the same way as well.
Left by Wayne on May 20, 2009 10:48 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
Hi
i can add items from My Windows Form Applications.
But, how can i add items under the folder on lists.

thanks for advice
Left by Burhan ERSOY on Sep 18, 2009 12:07 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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.
Left by eyan on Nov 22, 2009 4:54 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
What type of choice menu are you using? Drop Downlist, Rabio Button List, etc?

Let me know.
-Wayne
Left by Wayne Magnum on Nov 23, 2009 10:16 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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.
Left by Bubba Piersol on Jan 20, 2010 10:31 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
Hi,Have u worked with SharePoint 2010 web services to insert list item by a user with limited access?
Left by NishthaSB on Mar 25, 2010 1:20 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
I have not had a chance to working on SharePoint 2010. I will be starting a project which will involve SharePoint 2010.
Left by Wayne Magnum on Mar 31, 2010 7:40 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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!
Left by carla on Jun 11, 2010 4:22 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
I need to add Multi choice value, how I can add that thrugh web service
Left by SharepointDeve on Mar 20, 2011 1:37 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
how can i add xml data into sharepoint listcolumn using web services
Left by shravan on May 09, 2011 11:34 PM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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?
Left by Roni on Oct 05, 2011 3:19 AM

# re: SharePoint List WebService to Insert Item
Requesting Gravatar...
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.
Left by Elias on Feb 09, 2012 11:04 AM

Your comment:
 (will show your gravatar)


Copyright © Wayne H Magnum | Powered by: GeeksWithBlogs.net