Wednesday 5 June 2013

How to add a new list item to SharePoint using the List Item web service

How to add a new list item to SharePoint using the List Item web service

I have spent many hours trying to research something so simple that its almost embarassing. I have been a C# developer for 7 years, but am self-taught. Not this is an excuse for my inability to comprehend how to do such a simple task.
Thanks to Stamit’s CamlViewer 2007 and the U2UCamlCreator, I have been able to understand more about how CAML queries work. This has helped me understand the concepts behind adding new List Items.
First, Add a new Web Reference to your SharePoint site’s List webservice
(“http://YourSharePointServer/_vti_bin/lists.asmx”). Then, add the “System.Xml” namespace to your code.
   private void AddNewListItem()
{
   ReferenceToWebService.Lists myList = new ReferenceToWebService.Lists();
   myList.Credentials = System.Net.CredentialCache.DefaultCredentials;
   myList.Url = "http://YourSharePointSite/_vti_bin/lists.asmx";

   XmlDocument doc = new XmlDocument();
   XmlElement batch = doc.CreateElement("Batch");

   batch.SetAttribute("OnError", "Continue");
   batch.SetAttribute("ListVersion", "1");
   batch.SetAttribute("ViewName", "{GUID of View, including braces}");

   batch.InnerXml = "<Method ID='1' Cmd='New'>" +
      "<Field Name='ID'>New</Field>" +
      "<Field Name='Title'>Something</Field>" +
      "<Field Name='SomeField'>Something Else</Field></Method>";

   myList.UpdateListItems("{GUID of List, including braces}", batch);

}
I’m trying to populate a dropdownlist with data from a sharepoint list. Below is the code I’m using but am getting an error:
Object reference not set to an instance of an object DropDownList1.DataSource = list.Attributes["Location"].Value;
My Code is below:
Webservice.Lists myList = new WebApplication2.webservice.Lists(); myList.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlNode list = myList.GetList(“Printers”);
DropDownList1.DataSource = list.Attributes["Location"].Value;
DropDownList1.DataBind();

No comments:

Post a Comment