Procedimiento para actualizar elementos de listas

Última modificación: miércoles, 07 de julio de 2010

Hace referencia a: SharePoint Foundation 2010

Esta tarea de programación muestra cómo usar el método UpdateListItems del servicio web Lists para actualizar elementos de una lista a través de una aplicación de Microsoft Windows Forms.

Use un objeto XmlElement para crear un elemento Batch en el lenguaje de marcado de aplicaciones de colaboración (CAML) que pueda contener varios elementos Método y use el método UpdateListItems(String, XmlNode) para registrar los métodos y actualizar los elementos.

Nota

El número de elementos de lista que se pueden modificar mediante el método UpdateListItems en un único lote tiene un límite de 160.

El atributo Cmd de cada elemento Method determina la operación que se realiza en un elemento mediante la especificación de uno de los siguientes valores:

  • Delete -- Eliminar un elemento.

  • New -- Crear un elemento.

  • Update -- Modificar un elemento.

  • Move -- Mover un elemento.

Procedimientos

Antes de empezar, cree una aplicación de Windows Forms en Microsoft Visual Studio. Para obtener información acerca de cómo establecer una referencia web a un servicio web de SharePoint Foundation, vea Instrucciones para los servicios web.

Para agregar código para actualizar los elementos de una lista

  1. Abra Form1 en la vista Diseño, abra el Cuadro de herramientas y luego arrastre un control Button al formulario.

  2. Haga doble clic en el control Button para mostrar el Editor de código y, a continuación, agregue las siguientes líneas de código al controlador de eventos Button1_Click.

    'Declare and initialize a variable for the Lists Web service.
    Dim listService As 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://MyServer/sites/MySiteCollection/_vti_bin/Lists.asmx"
    
    'Get Name attribute values (GUIDs) for list and view. 
    Dim ndListView As System.Xml.XmlNode = listService.GetListAndView("MyList", "")
    Dim strListID As String = ndListView.ChildNodes(0).Attributes("Name").Value
    Dim strViewID As String = 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. 
    Dim doc As New System.Xml.XmlDocument()
    Dim batchElement As System.Xml.XmlElement = doc.CreateElement("Batch")
    batchElement.SetAttribute("OnError", "Continue")
    batchElement.SetAttribute("ListVersion", "1")
    batchElement.SetAttribute("ViewName", strViewID)
    
    'Specify methods for the batch post using CAML. To update or delete, 
    'specify the ID of the item, and to update or add, specify 
    'the value to place in the specified columns.
    batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" +
       "<Field Name='ID'>6</Field>" +
       "<Field Name='Title'>Modified sixth item</Field></Method>" +
       "<Method ID='2' Cmd='Update'><Field Name='ID'>7</Field>" +
       "<Field Name='Title'>Modified seventh item</Field></Method>" +
       "<Method ID='3' Cmd='Delete'><Field Name='ID'>5</Field>" +
       "</Method><Method ID='4' Cmd='New'>" +
       "<Field Name='Title'>Added item</Field></Method>"
    
    'Update list items. This example uses the list GUID, 
    'which is recommended, but the list display name will also work.
    listService.UpdateListItems(strListID, batchElement)
    
    /*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://MyServer/sites/MySiteCollection/_vti_bin/Lists.asmx";
    
    /*Get Name attribute values (GUIDs) for list and view. */
    System.Xml.XmlNode ndListView = listService.GetListAndView("MyList", "");
    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);
    
    /*Specify methods for the batch post using CAML. To update or delete, 
    specify the ID of the item, and to update or add, specify 
    the value to place in the specified column.*/
    batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" +
       "<Field Name='ID'>6</Field>" +
       "<Field Name='Title'>Modified sixth item</Field></Method>" +
       "<Method ID='2' Cmd='Update'><Field Name='ID'>7</Field>" +
       "<Field Name='Title'>Modified seventh item</Field></Method>" +
       "<Method ID='3' Cmd='Delete'><Field Name='ID'>5</Field>" +
       "</Method><Method ID='4' Cmd='New'>" +
       "<Field Name='Title'>Added item</Field></Method>";
    
    /*Update list items. This example uses the list GUID, which is recommended, 
    but the list display name will also work.*/
    try
    {
       listService.UpdateListItems(strListID, batchElement);
    }
    catch (SoapServerException ex)
    {
       MessageBox.Show(ex.Message);
    }
    

    Nota

    Al registrar el método UpdateListItems se produce silenciosamente un error si un elemento especificado no existe. El identificador de un elemento eliminado se mantiene después de una operación de eliminación. Por lo tanto, en el ejemplo se elimina el quinto elemento de la lista, pero no se vuelve a asignar el número 5 como identificador de otro elemento.

  3. En el menú Depurar, haga clic en Iniciar depuración o presione F5 para probar el formulario.