Friday, November 6, 2009

Create List Item using SP List Web Service

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 = "" + ContactName + "" + PhoneNumber + "" + Website + "" + SecretIdentity + ""; //"" + "New" + "" + ContactName + "" + "" + PhoneNumber + "" + "" + Website + "" + "" + SecretIdentity + "" + "";

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

0 comments: