Compartilhar via


COMO: Atualizar itens de lista

Esta tarefa programação mostra como usar o UpdateListItems M:websvcLists.Lists.UpdateListItems(System.String,System.Xml.XmlNode) do Lists serviço da Web para atualização itens em uma lista por um aplicativo do Windows Microsoft.

Use um objeto System.Xml.XmlElement System.Xml.XmlElement criar um elemento 2d716503-4843-4f8c-86d6-392707ce9095 em lote em Collaborative Application Markup Language (CAML) que pode conter múltiplo elementos bfcb7a97-c9e7-4b16-9a20-9c023c9ffc2b método e use o UpdateListItems M:websvcLists.Lists.UpdateListItems(System.String,System.Xml.XmlNode) método para postagem os métodos e atualização itens. O atributo Cmd comando de cada elemento bfcb7a97-c9e7-4b16-9a20-9c023c9ffc2b método determina a operação que será realizada em um item por especificando uma do seguinte valores:

  • Delete--excluir um item.

  • New--criar um item.

  • Update--modificar um item.

Procedimentos

Antes de começar, crie um aplicativo do Windows conforme descrito em Guia de Introdução Com programaticamente personalizar uma Web Site SharePoint em Visual Studio. Para obter informações sobre configuração uma referência da Web para um Windows SharePoint Services serviço da Web, consulte Diretrizes de serviço da Web.

Observação

O exemplo pressupõe a existência de uma lista nomeado "MyList" que contém pelo menos

Para codificar adicionar a atualização lista Itens

  1. Abra Form1 no modo Design, aberto o a Caixa de ferramentas e, em seguida, arrastar um botão controle até a forma.

  2. Clique duas vezes o controle button1 para exibir a editor de códigos e, em seguida, adicionar o seguinte clique linhas de código para o Click manipulador de eventos:

                              '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);
    }
    

    Observação

    Lançar o método UpdateListItems UpdateListItems silenciosamente falhará se um item especificado não existe.A identificação para um item excluído é mantida após uma operação de exclusão.Conseqüentemente, o exemplo exclui o quinto item na lista, mas não é reatribuído 5 como a identificação para outro item.

  3. Sobre o clique menu Debug iniciar depuração , ou pressionar F5 , para testar a forma.