Sunday, August 28, 2011

Insert a Sharepoint list item from web services

The following code is used to insert an item to a list using SharePoint Web Services.

        /// <summary>
        /// Method to insert picture URL to a list
        /// </summary>
        /// <param name="pictureURL">URL of the picture</param>
        /// <param name="currentlLoginID">Current logged in user</param>
        private void InsertItem(string pictureURL,string currentlLoginID)
       /*Declare and initialize a variable for the Lists Web service.*/
            spsService.Lists listService = new spsService.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 = "http://spsService/sites/MP/_vti_bin/Lists.asmx";

            System.Xml.XmlNode ndListView = listService.GetListAndView("Team Profiles", "");
            string listName = ndListView.ChildNodes[0].Attributes["Name"].Value;
            string viewName = ndListView.ChildNodes[1].Attributes["Name"].Value;

             XmlDocument xmlDoc = new XmlDocument();
            /* Declare an XmlNode object and initialize it with the XML response from the GetListItems method.*/
            System.Xml.XmlNode nodeListItems = listService.GetList(listName);

            string sBatch = string.Empty;        
            string uid = "-1;#" + currentlLoginID;

            //Query to insert data
            sBatch = "<Method ID=\"1\" Cmd=\"New\">";
            sBatch += "<Field Name=\"ID\">New</Field>";
            sBatch += "<Field Name=\"User_Picture\">" + pictureURL + "</Field>";
            sBatch += "<Field Name=\"UID\" >" + uid + "</Field>";
            sBatch += "</Method>";

            XmlElement batch_element = xmlDoc.CreateElement("Batch");
            batch_element.SetAttribute("OnError", "Continue");
            batch_element.SetAttribute("ViewName", viewName);

            batch_element.InnerXml = sBatch;
            listService.UpdateListItems(listName, batch_element);


  1. Hello If I have to Insert Multiple Look Up Than How Can i Insert , Example I have UserMaster and i pass in this list as Look Up.... sBatch += "" + uid + "";

    Now i have to Insert 2 User ID As Multiple Selection of look Up How Can I Achieve This Functionality ?

  2. I would recommend you to first hard code the values in the uid string field and try. Use semicolon as separator.
    string uid = "-1;#" + currentlLoginID+";-2;#"+loginID2;