Click here to Skip to main content
15,885,782 members
Articles / Programming Languages / C#
Article

Adding values to sharepoint lists

Rate me:
Please Sign up or sign in to vote.
2.70/5 (5 votes)
27 Jan 2008CPOL4 min read 139.1K   23   10
This article will create a very simple C# application that demonstrates how an application can add items to a Windows SharePoint Service 3.0 list using web services.

Introduction

This article will create a very simple C# application that demonstrates how an application can add items to a Windows SharePoint Service 3.0 list using web services.

Background

As my company starts to use SharePoint for more applications I have started thinking of many applications where it would be useful to programmatically add items to a SharePoint task list. Once the item is in the task list you can take advantage of all of the built in SharePoint functionality such as user alerts or workflows without writing any additional code.

Items can be added to a SharePoint list programmatically using the SharePoint object model. However, if you want to be able to add items from applications running on any server, included those that don’t have direct access to the SharePoint objects, you can use one of the many web services SharePoint makes available.

Windows SharePoint Service 3.0 comes with over 20 web services that allow you to access a range of functionality from administrative functionality to site creation. This article will focus on the Lists web service and demonstrate how to use to it to add and read items from a list.

The Lists Web Service

As with any web service the first thing you need to do is create a reference to the web service. The URL to the Lists service is

    http://<site>/_vti_bin/Lists.asmx

The _vti_bin directory is available from every site on the SharePoint server. It is important to use the Site the list is contained in. For example, the server I developed this sample on was named SPDEV-APP01. The task list I was using was in a site named Subsite. When I first tried this I used the following URL for the web service:

    http://SPDEV-APP01/_vti_bin/Lists.asmx

This URL did not work because the list I wanted to use was not contained in the top level web site. The correct URL is:

    http://SPDEV-APP01/Subsite/_vti_bin/Lists.asmx

For some reason when I first changed the properties of the Web Reference URL Visual Studio did not change the value in App.Config. Once I corrected the App.Config I had a web reference named App03Lists that can be used to access my task list.

Using List GUIDs

The methods that will be used in the examples below require the GUID of the SharePoint list and the view. There are a few different ways to find GUIDs used by SharePoint but the method that I found the easiest was to use a GUID picker utility. I found this utility on a Ronalus blog posting at

    http://blogs.msdn.com/ronalus/archive/2007/09/08/a-little-guid-picker.aspx

Adding Values to the List

The UpdateListItems method of the Lists service will be used to add a new item in the list. This methods takes the GUID of the list and a Batch of XML. The batch specifies a series of commands that can run to add, update or delete items from the list. The following is the very simple Batch used in this example:

<Batch OnError="Continue" ViewName="{D0E978D3-4D39-4CBE-ACEC-BCFB22344252}">
    <Method ID='1' Cmd='New'>
        <Field Name='Title'>The New Task Title</Field>
     </Method>
</Batch>

This Batch executes one command that adds a new item to the list and sets the field named Title to “The New Task Title.” The can obviously be extended to add multiple items at once and set multiple field values. It is important to note that the fields used in the batch must be available in the view specified by in the ViewName attribute.

The following is the complete code that adds a value to the task list:

C#
App03Lists.Lists listService = new App03Lists.Lists();

// SharePoint Web Serices require authentication
listService.Credentials= System.Net.CredentialCache.DefaultCredentials;  

String newIssueTitle = "Programmatically added issue 2";

String listGUID = "{D20D26A7-3935-43F8-848F-03612AF782DE}";
String activeItemViewGUID = "{D0E978D3-4D39-4CBE-ACEC-BCFB22344252}";

string strBatch =
	"<Method ID='1' Cmd='New'>" +
	String.Format("<Field Name='Title'>{0}</Field>", newIssueTitle) +
	"</Method>";

XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");
elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ViewName", activeItemViewGUID);
elBatch.InnerXml = strBatch;
XmlNode ndReturn = listService.UpdateListItems(listGUID, elBatch);

The complete documentation for UpdateListItems can be found here:

    http://msdn2.microsoft.com/en-us/library/lists.lists.updatelistitems.aspx

Reading Values from the List

One of the places I expect to use this functionality will be a service that runs every five minutes to check for failed SQL jobs. When a job fails, the program will create a task in the task list. It is very likely that the service will run multiple times before a failed job is fixed. In order to prevent multiple tasks from being created for the same failed job I wanted to read the list of active tasks to ensure duplicate tasks are not created.

The GetListItems method of the Lists web service will be used to read the existing tasks from the list. This method takes several parameters that can be used to specify a query to select rows, a list of fields to be returned, the number of rows to be returned, etc.; for this simple example only the first two parameters will be used, the list GUID and the view GUID. Only these parameters are required because the view being used, active items, already performs the proper row and field selection.

The following example adds the logic to:

  1. select tasks from the active items view
  2. add the new tasks if it is not already in the items view

C#
App03Lists.Lists listService = new App03Lists.Lists();

// SharePoint Web Serices require authentication
listService.Credentials= System.Net.CredentialCache.DefaultCredentials;  

String newIssueTitle = "Programmatically added issue 2";

String newIssueTitle = "Programmatically added issue 2";

String listGUID = "{D20D26A7-3935-43F8-848F-03612AF782DE}";
String activeItemViewGUID = "{D0E978D3-4D39-4CBE-ACEC-BCFB22344252}";

// first check if item is already in the list
XmlNode activeItemData = listService.GetListItems(listGUID, activeItemViewGUID, null, null, "", null, "");
if (!activeItemData.InnerXml.Contains(newIssueTitle))
{
    // item does not exist in active view so add it
    string strBatch =
        "<Method ID='1' Cmd='New'>" +
        String.Format("<Field Name='Title'>{0}</Field>", newIssueTitle) +
        "</Method>";

    XmlDocument xmlDoc = new System.Xml.XmlDocument();
    System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");
    elBatch.SetAttribute("OnError", "Continue");
    elBatch.SetAttribute("ViewName", activeItemViewGUID);
    elBatch.InnerXml = strBatch;
    XmlNode ndReturn = listService.UpdateListItems(listGUID, elBatch);

}

The complete documentation for GetListItems can be found here:

    http://msdn2.microsoft.com/en-us/library/lists.lists.getlistitems.aspx

Conclusion

This is a very simple example that adds one item to a SharePoint task list. It can easily be extended to manipulate any type of SharePoint list including document libraries. The code shown above can be wrapped in a windows service or any other type of C# application.




License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalerror Pin
tapsbops13-Jun-11 1:24
tapsbops13-Jun-11 1:24 
Generaldoes not work when deployed on the web server Pin
walerhola21-Feb-11 4:43
walerhola21-Feb-11 4:43 
Generalgetting error while updating the list Pin
vimalkumarsinghal3-Dec-09 20:31
vimalkumarsinghal3-Dec-09 20:31 
Generalworking with sharepoint list Pin
itsaranga29-Sep-09 1:47
itsaranga29-Sep-09 1:47 
working with sharepoint list

to add values

item["Field name"] ="your value";

after adding values do this

item .SystemUpdate(false);
item .Update();
item .Update();
GeneralCodes runs but I don't see the item appear in sharepoint [modified] Pin
Hawkmoth24-Sep-09 0:44
Hawkmoth24-Sep-09 0:44 
GeneralRe: Codes runs but I don't see the item appear in sharepoint Pin
Hawkmoth24-Sep-09 2:43
Hawkmoth24-Sep-09 2:43 
GeneralBatch in the code different from the example Pin
AACINC11-Sep-09 6:24
AACINC11-Sep-09 6:24 
QuestionSo how do I find the GUID? Pin
W1NGL17-Oct-08 10:47
W1NGL17-Oct-08 10:47 
QuestionHow to Get the Id of existing item from list sub folder Pin
T.Ashraf17-Jul-08 5:37
T.Ashraf17-Jul-08 5:37 
GeneralGood guidance Pin
bburgon4230-Jan-08 9:46
bburgon4230-Jan-08 9:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.