There was an error in this gadget

Thursday, December 9, 2010

Adding list item to SharePoint List using List web service

In this post, I will show you how to add list item to the list using SharePoint web service.

I am writing a code in Windows Application and I have taken reference of Lists.asmx of respective site.

I have PDFReports as list in my site and in that I have three columns. Name of the columns are title, group which is Choice column (Doc,Pdf,Excel) and Price which is number.

private void btnReports_Click(object sender, EventArgs e)
{
string strQuery = "<Method ID='1' Cmd='New'>" +
"<Field Name='Title'>" + "Report1" + "</Field>" +
"<Field Name='Price'>" + 1000 + "</Field>" +
"<Field Name='Group'>" + "Doc" + "</Field></Method>";

DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{site url}/_vti_bin/lists.asmx";

String listName = "PDFReports";

XmlDocument xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

elBatch.SetAttribute("OnError", "Continue");

elBatch.SetAttribute("ListVersion", "1");

elBatch.InnerXml = strQuery;

XmlNode ndReturn = objLists.UpdateListItems(listName, elBatch);

string result = ndReturn.OuterXml.ToString();


}


Just make sure that you pass proper credentials to the web service. Rest the code itself is self explanatory.

Just observe the result string above, and see ErrorCode element in it, it should be 0x00000000. If it is, then it is a success, else there is some error and item has not been added.

If we have Look Up Columns then change the query as 

Either you can mention in Field tag that this is the lookup field or you can directly reference that look up value by mentioning; # sign in between.

Below are the examples that describe both the ways.

1) "<Field Name='Group' Type='Lookup'>" + 2 + "</Field></Method>";

2) "<Field Name='Group'>" + "2;#pdf" + "</Field></Method>";


No comments:

Post a Comment