Submitting Data from InfoPath 2007 to a SharePoint List

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Summary:   Learn how to create a solution for submitting data from a Microsoft Office InfoPath 2007 form to add, update, or delete items to a list in Windows SharePoint Services 3.0 or Microsoft Office SharePoint Server 2007. (18 printed pages)

Mark Roberts, Microsoft Corporation

February 2008

Applies to:   Microsoft Office InfoPath 2007, Windows SharePoint Services 3.0, Microsoft Office SharePoint Server 2007

Contents

  • Overview of Submitting to a SharePoint List from InfoPath Forms

  • Creating an InfoPath Form Template to Submit Items to a SharePoint List

  • Creating the SharePoint List

  • Creating the CAML XML Fragment

  • Creating the Form Template and Adding Data Connections to the List

  • Identifying the List GUID

  • Adding Controls to Display the Current Items in the List

  • Adding Fields and Controls for Submitting New Items to the List

  • Cleaning Up the Layout of the Form

  • Adding a Connection to the Lists Web Service and Specifying the Parameters of the UpdateListItems Method

  • Adding Submit Functionality

  • Testing the Form

  • Conclusion

  • Acknowledgments

  • Additional Resources

Overview of Submitting to a SharePoint List from InfoPath Forms

Submitting InfoPath forms to a SharePoint form library is quite simple: Just use the Data Connections command on the Tools menu to add a Submit data connection to your form template, and continue from there. However, using an InfoPath form to submit data to a SharePoint list is more complex and requires that you write some code. In this article, we take a look at the steps that are required to do this. The sample solution described in this article enables you to add, update, or delete items in a contacts list on a Windows SharePoint Services 3.0 or Office SharePoint Server 2007 site from an InfoPath form.

Creating an InfoPath Form Template to Submit Items to a SharePoint List

The high-level steps for creating a form template that can submit items to a SharePoint list are as follows:

  1. Create the SharePoint list.

  2. Create the Collaborative Application Markup Language (CAML) XML fragment that InfoPath submits to the UpdateListItems Web service method of the Lists Web service to add the new item to the list.

  3. Create the form template and add the required data connections.

  4. Identify the GUID used as the ID for the list.

  5. Add controls to the form template to display the current items in the list.

  6. Add fields and controls for entering new items to submit to the list.

  7. Add a connection to the SharePoint Lists Web service and define the parameters for calling the UpdateListItems Web method.

  8. Add the event handler code required to submit additions, updates, and deletions from the list.

  9. Test the form.

The following sections provide details about each of these steps.

Creating the SharePoint List

The first step is to create a custom list on a Windows SharePoint Services 3.0 or Office SharePoint Server 2007 site. The following procedure creates a simple contacts list. The first four columns contain the contact data that is visible in the list. The Changed and Delete columns are not displayed in the list. The event handler code in the form template uses these columns to track whether the list item needs to be updated or deleted.

To create the SharePoint list

  1. On the Site Actions menu, click Create.

  2. On the Create page, click Custom List.

  3. Name the list MyContacts, and then click Create.

  4. On the Settings menu, click List Settings.

  5. In the Columns section, click Create Column.

  6. Add each of the columns shown in Table 1.

Table 1 List column names and data types

Name

Data Type

FirstName

Single line of text

LastName

Single line of text

Phone

Single line of text

Email

Single line of text

Changed

Yes/No (set Default value to No, and clear the Add to default view check box)

Delete

Yes/No (set Default value to No, and clear the Add to default view check box)

Make a note of the URL for the list. You will need it later to connect your InfoPath form template to the list.

Creating the CAML XML Fragment

The next step is to create a CAML XML fragment that specifies the columns in an item that is being submitted to the list. This XML fragment is submitted as the argument to the updates parameter of the UpdateListItems method of the SharePoint Lists Web service. The CAML elements used in the XML fragment are the Batch Element element, the Method Element (View) element, and the Field Element (List - Definition) element.

After the user specifies the values to add or update, or whether to delete an item, code in the InfoPath form sets the appropriate values in the CAML fragment and then submits it to the UpdateListItems method. By default, the Cmd attribute of the Method element is set to New to add a new item in the list, but code in the form changes the Cmd attribute to "Update" or "Delete" depending on the user's actions in the form.

Also, by default, the ID attribute of the Method element is set to "1". When form code submits a new item to the Web service, the ID attribute is ignored. But if the user updates or deletes an item in the form, code in the form retrieves the value of the ID column for that particular item and sets the ID attribute in the XML fragment before submitting it to the Web service.

To create the CAML XML fragment

  1. Start Notepad (or any text editor).

  2. Copy and paste the following XML code.

    <Batch OnError="Continue">
        <Method ID="1" Cmd="New">
            <Field Name='Title'></Field>
            <Field Name="FirstName"></Field>
            <Field Name="LastName"></Field>
            <Field Name="Phone"></Field>
            <Field Name="Email"></Field>
            <Field Name="Delete">false</Field>
            <Field Name="Changed">false</Field>
            <Field Name="ID"></Field>
        </Method>
    </Batch>
    
  3. Save this file as Add List Item Template.xml

The next section shows you how to add the CAML XML file to the form template as a secondary data connection.

Creating the Form Template and Adding Data Connections to the List

In this step, you create the form template and add data connections to the Add List Item Template.xml file and the MyContacts list.

To create the InfoPath form template and add data connections to the list

  1. Start Office InfoPath 2007.

  2. In the Getting Started dialog box, click Design a Form Template.

    (If the Getting Started dialog box is not visible, click Design a Form Template on the File menu.)

  3. In the Based on list, click Blank, clear the Enable browser-compatible features only check box, and then click OK.

  4. On the Tools menu, click Data Connections, and then click Add.

  5. In the Data Connection Wizard dialog box, click Create a new connection to, click Receive data, and then click Next.

  6. Click XML document, and then click Next.

  7. Click Browse, locate and select the Add List Item Template.xml file that you created in the "To create the CAML XML fragment" procedure, and then click Next.

  8. Click the Include the data as a resource file in the form template or template part, and then click Next.

  9. Ensure that the Automatically retrieve data when the form is opened check box is selected, and then click Finish.

  10. In the Data Connections dialog box, click Add.

  11. Click Create a new connection to, click Receive data, and then click Next.

  12. Click SharePoint library or list, and then click Next.

  13. Type the URL to the MyContacts list that you created in the "To create the SharePoint list" procedure, and then click Next.

  14. In the Select a list or library list, select MyContacts, and then click Next.

  15. Select the Title and ID fields along with the six custom fields that you created (FirstName, LastName, Phone, Email, Changed, and Delete), and then click Next twice.

  16. Make sure that the Automatically retrieve data when the form is opened check box is selected, and then click Finish.

  17. Click Close to close the Data Connections dialog box.

Identifying the List GUID

Each SharePoint list is identified by a GUID. To submit items to a SharePoint list, you must know the GUID for that list. These next steps show you how to identify the GUID for your MyContacts list.

To identify the list GUID

  1. Open a browser and navigate to the MyContacts list.

  2. On the Settings menu, click List Settings.

  3. In the browser’s address bar, you will see the URL appended with List=

  4. Copy everything after the equal sign and paste this into a text editor because you will need this value later.

    Important noteImportant

    The list GUID must be formatted as: {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. If the list GUID has the hyphens and braces escaped (with %7B for the opening brace, %2D for the hyphens, and %7D for the closing brace), you must replace the escaped characters with actual braces and hyphens. When you use this GUID later, it must appear as follows: {1E76517B-2C36-4473-A420-A737D98589BC}

Adding Controls to Display the Current Items in the List

In this step, you add a Repeating Table control to display the current items in the MyContacts list.

To add controls to display items in the list

  1. Open the Data Source task pane.

  2. In the Data Source drop-down list, click the MyContacts (Secondary) connection.

  3. Expand the dataFields folder, right-click the MyContacts folder, and then click Repeating Table.

    This adds a Repeating Table control bound to the fields from that connection to your view.

    You do not need the ID and Changed fields bound to the repeating table, so the next step describes how to delete them.

  4. In the Repeating Table control, right-click the ID column, point to Delete, and then click Columns. Repeat this step to delete the Changed column.

  5. At run time, a user can select the Check Box control bound to the Delete field to indicate whether to delete the item, so change the Delete field's column heading to read Delete?

  6. Select the Delete? column heading, and then click the Center button on the Formatting tool bar.

  7. Delete the label next to the check box bound to the Delete field, select the check box, and then click the Center button on the Formatting tool bar.

Adding Fields and Controls for Submitting New Items to the List

In this step, you add a group and fields to the form's main data source to temporarily contain the new items a user adds to the list. Then you add a Repeating Table control, which is bound to this group, to the form's view. You also add an AddContacts field to the main data source and bind that to a Check Box control that the user selects to add new contact items to the list. Finally, you add a ListName field to the main data source that is used by form code to specify the GUID of the list when a user submits items to the list.

To add fields and controls for submitting new items to the list

  1. In the Data Source drop-down list, click Main.

  2. In the Data Source pane, right-click the myFields folder, and then click Add.

  3. Add a True/False field named AddContacts, set the Default Value to FALSE, and then click OK.

  4. Drag AddContacts from the Data Source and drop it below the repeating table you added to the form in the previous procedure.

    This adds a Check Box control that is used at run time to display the repeating table for adding new items.

  5. Change the label of the AddContacts check box to read Add New Contacts?

  6. Right-click the myFields folder, and then click Add.

  7. Add a Group named gpContacts.

  8. Right-click the gpContacts folder, and then click Add.

  9. Add a Group named gpContact, select the Repeating check box, and then click OK.

  10. Right-click the gpContact folder, and then click Add.

  11. Add five Text fields named Title, FirstName, LastName, Email, and Phone.

  12. Right-click the gpContacts folder, and then click Section with Controls.

    This adds a Section control that contains a Repeating Table control bound to the gpContact group and the fields it contains.

  13. Right-click the Section control that you added in step 12, and then click Conditional Formatting.

  14. In the Conditional Formatting dialog box, click Add.

  15. Under If this condition is true, set the condition to AddContacts is equal to FALSE.

  16. Under Then apply this formatting, click Hide this control.

  17. Click OK twice.

  18. Right-click the Repeating Table control that you added in step 12, and then click Repeating Table Properties.

  19. On the Data tab, select the Show insert button and hint text check box, type Add New Contact in the text box, and then click OK.

  20. Right-click the myFields folder, click Add, and then add a Text field named ListName.

  21. Set the Default Value property of the ListName field to the value of the GUID of your list (which you determined by using the procedure in the "Identifying the List GUID" section).

    Form code uses this field to specify the identifier of the list when a user performs the submit operation.

Cleaning Up the Layout of the Form

You should now have the controls that are required for viewing and entering data in the form. But before you continue, clean up the layout using a Layout Table, and add some text to identify what each repeating table is used for.

To add a layout table and labels

  1. Click above the two Repeating Table controls that you added in the earlier procedures.

  2. On the Table menu, point to Insert, and then click Layout Table.

  3. Set the Number of columns to 1 and set the Number of rows to 2, and then click OK.

  4. Right-click the topmost Repeating Table control, click Cut, and then paste it into the first row of the layout table.

  5. Select the Check Box bound to the AddContacts field and the Add New Contacts? label, right-click the selected items, click Cut, and then paste them below the first repeating table.

  6. Right-click the Section control that contains the second Repeating Table control, click Cut, and then paste it into the second row of the layout table.

  7. Right-click the title row of the topmost Repeating Table control, point to Insert, and then click Rows Above.

  8. Select all of the cells in the new row, right-click the selected cells, and then click Merge Cells.

  9. Type Current contacts in the list: in the new row.

  10. Repeat steps 7 and 8 for the second repeating table, and then type New contacts to be added: in the new row.

    When you are finished, your form should look like Figure 1:

    Figure 1. Final design of the form

    Final design of the form

Adding a Connection to the Lists Web Service and Specifying the Parameters of the UpdateListItems Method

To add items to the SharePoint list, a client application uses the UpdateListItems method of the SharePoint Lists Web service.

The UpdateListItems Web service method requires two parameters: the listName parameter that specifies the name of the list, and the updates parameter that accepts a Batch element XML fragment. The Batch element XML fragment specifies the items to post to the list and whether to perform an add, update, or delete operation.

Now that you have the ListName field that contains the GUID for the list, and the Add List Item Template data connection that describes the data structure of the item to add, you have all the necessary information to define the connection for submitting items to the list.

Important noteImportant

For the data connection to the Lists Web service to work correctly, the URL you enter in step 4 of this procedure must correspond to the location of your MyContacts list. If the list is located directly off the root Web of your SharePoint server, the URL will be in this form:

http://servername/_vti_bin/lists.asmx

If the list is located in a site on your SharePoint server, the URL will be in this form:

http://servername/sitename/_vti_bin/lists.asmx

To connect to the Lists Web Service and specify the parameters of the UpdateListItems method

  1. On the Tools menu, click Data Connections, and then click Add.

  2. In the Data Connection Wizard dialog box, click Create a new connection to, click Submit data, and then click Next.

  3. Click To a Web service, and then click Next.

  4. Type the URL to the Lists Web service (see previous note), and then click Next.

  5. In the Select an operation list, select the UpdateListItems operation, and then click Next.

  6. In the Parameters list, double-click the tns:listName parameter name, and then assign the ListName field as the value to pass for this parameter.

  7. Double-click the tns:updates parameter name, select the Add List Item Template (Secondary) data source, select the Batch folder, and then click OK.

  8. In the Include drop-down list, select XML subtree, including selected element, and then click Next.

  9. Click Finish, and then click Close.

Adding Submit Functionality

Now that your form template has all the data connections and controls that are required for displaying data in the list, you need to add event handler code for submitting the items to add, update, or delete from the list.

Adding Event Handler Code to the Add New Contacts Check Box

By default, conditional formatting set on the repeating table for adding new contacts hides the table. To display the repeating table, you must add an event handler to the check box that is bound to the addContacts field. The event handler code runs when the Changed() event of the addContacts field is raised (which occurs when the user selects the check box). The code adds a new blank row to the repeating table, which displays the control and provides an empty row for entering a new contacts list item. The user can add rows by clicking Add New Contact below the first row in the table. If the user clears the check box, the event handler code removes the blank row (and any other rows in the control), which hides the repeating table. The code to remove the blank row depends on the ClearEnteredValues custom function, which is described in the following procedure.

To add event handler code to the Add New Contacts check box

  1. Right-click the check box that is bound to the AddContacts field, point to Programming, and then click Changed Event.

  2. Add the following code to the AddContacts_Changed event handler.

    try
    {
       // Get a reference to the form's XmlNamespaceManager object.
       XmlNamespaceManager ns = this.NamespaceManager;
    
       // Create an XPathNavigator object for the form's main data
       // source.
       XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();
    
       // If the check box is set to true, add a new row so the user 
       // can add a new contact.
       if (e.Site.Value == "true")
       {
          XPathNavigator xnTable = 
             xnDoc.SelectSingleNode("/my:myFields/my:gpContacts", ns);
          xnTable.AppendChild("<my:gpContact><my:Title /><my:FirstName /><my:LastName /><my:Email /><my:Phone /></my:gpContact>");
       }
       else
       {
          // If the user clears the check box, remove the added row.
          ClearEnteredValues(xnDoc);
       }
    }
    catch (Exception ex)
    {
       MessageBox.Show("The following error occurred: " + ex.Message);
       throw;
    }
    
  3. Add the following code for the custom ClearEnteredValues function.

    private void ClearEnteredValues(XPathNavigator xnDoc)
    {
       try
       {
          // Get a reference to the form's XmlNamespaceManager object.
          XmlNamespaceManager ns = this.NamespaceManager;
    
          // Create an XPathNodeIterator object to get a count of the 
          // rows in the repeating table used to add new Contacts.
          XPathNodeIterator xi = xnDoc.Select(
             "/my:myFields/my:gpContacts/my:gpContact", ns);
          int rowCount = xi.Count;
    
          if (rowCount > 0)
          {
             // Get the first and last rows (nodes) in the 
             // repeating table.
             XPathNavigator firstNode = xnDoc.SelectSingleNode(
                "/my:myFields/my:gpContacts/my:gpContact[1]", ns);
             XPathNavigator lastNode = xnDoc.SelectSingleNode(
                "/my:myFields/my:gpContacts/my:gpContact[" +
                rowCount + "]", ns);
    
             // Delete the existing nodes using the DeleteRange method.
             firstNode.DeleteRange(lastNode);
          }
    
         // Clear the check box. 
         xnDoc.SelectSingleNode(
            "/my:myFields/my:AddContacts", ns).SetValue("false");
       }
    
       catch (Exception ex)
       {
          MessageBox.Show("The following error occurred: " + 
             ex.Message);
          throw;
       }
    }
    
  4. Save your additions, and switch back to InfoPath form design view.

Adding Event Handler Code to Flag Updated Items

When the user changes items in the repeating table bound to the MyContacts group that displays current contacts in the list, code is required to set the Changed column to true to flag that the item was updated. The code for submitting data to the list uses the value of the Changed column to determine whether to submit that item. Additionally, the event handler code must check whether the user selected the Delete check box and not set the Changed column in this case.

To add event handler code to flag updated items

  1. Right-click the header row of the repeating table bound to the MyContacts group, point to Programming, and then click Changed Event.

  2. Add the following code to the MyContacts__MyContacts_Changed event handler.

    try
    {
       // Get a reference to the form's XmlNamespaceManager object.
       XmlNamespaceManager ns = this.NamespaceManager;
    
       // See if values have been changed.
       if (e.Operation == XmlOperation.ValueChange)
       {
          // Set the Changed field to "true" only if the Delete
          // check box is not selected.
          if (e.Site.SelectSingleNode("@Delete", ns).Value != "true")
          {
             e.Site.SelectSingleNode("@Changed", ns).SetValue("true");
          }
       }
    }
    catch (Exception ex)
    {
       MessageBox.Show("The following error occurred: " + ex.Message);
       throw;
    }
    
  3. Save your additions, and switch back to InfoPath form design view.

Adding a Button for Submitting Items in the List

This section describes how to add a Button control and its event handler code to the form for submitting changes to the form. Note that the code for this button handles all operations the user can perform in the form: adding new items, updating existing items, and deleting existing items.

To add a button for updating items in the list

  1. In the Design Tasks task pane, click Controls.

  2. Drag a Button control below the second repeating table.

  3. Double-click the button to display its properties dialog box.

  4. On the General tab of the Button Properties dialog box, change the Label property to Submit Changes, and change the ID property to btnSendChanges.

  5. Click Edit Form Code to open the code editor.

  6. Add the following code to the btnSendChanges_Clicked event handler.

    try
    {
       // Get a reference to the form's XmlNamespaceManager object.
       XmlNamespaceManager ns = this.NamespaceManager;
    
       // Create a DataSource object for the MyContacts 
       // list data connection.
       DataSource dsContacts = this.DataSources["MyContacts"];
    
       // Create an XPathNavigator object for the MyContacts 
       // data connection.
       XPathNavigator xnContacts = dsContacts.CreateNavigator();
    
       // Create an XPathNodeIterator object for the MyContacts 
       // data connection to enumerate the existing contacts.
       XPathNodeIterator xiContacts = xnContacts.Select(
          "/dfs:myFields/dfs:dataFields/dfs:MyContacts", ns);
    
       // Create a DataSource object for the Add List Item Template
       // data connection.
       DataSource dsCAML = this.DataSources["Add List Item Template"];
    
       // Create an XPathNavigator object for the 
       // Add List Item Template data connection.
       // This is used to set the values in the CAML XML file.
       XPathNavigator xnCAML = dsCAML.CreateNavigator();
    
       // Create a WebServiceConnection object for submitting 
       // to the Lists Web service data connection.
       WebServiceConnection wsSubmit = 
          (WebServiceConnection)this.DataConnections[
          "Web Service Submit"];
    
       // Create an XPathNavigator object for the form's 
       // main data source.
       XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();
    
       // Create an XPathNodeIterator object for the new contacts.
       XPathNodeIterator xiNewContacts = xnDoc.Select(
          "/my:myFields/my:gpContacts/my:gpContact", ns);
    
       // See if any new contacts have been added.
       if (xiNewContacts.Count > 0)
       {
          while (xiNewContacts.MoveNext())
          {
             // Set the values in the Add List Item Template 
             // XML file using the values in the new row.
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='Title']", ns)
                .SetValue(xiNewContacts.Current.SelectSingleNode(
                "my:Title", ns).Value);
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='FirstName']", ns)
                .SetValue(xiNewContacts.Current.SelectSingleNode(
                "my:FirstName", ns).Value);
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='LastName']", ns)
                .SetValue(xiNewContacts.Current.SelectSingleNode(
                "my:LastName", ns).Value);
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='Phone']", ns)
                .SetValue(xiNewContacts.Current.SelectSingleNode(
                "my:Phone", ns).Value);
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='Email']", ns)
                .SetValue(xiNewContacts.Current.SelectSingleNode(
                "my:Email", ns).Value);
    
             // Set the values of the Changed and Delete columns to
             // "FALSE".
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='Changed']", ns)
                .SetValue("FALSE");
             xnCAML.SelectSingleNode(
                "/Batch/Method/Field[@Name='Delete']", ns)
                .SetValue("FALSE");
    
             // Set the value of Cmd attribute to "New".
             xnCAML.SelectSingleNode("/Batch/Method/@Cmd", ns)
                .SetValue("New");
    
             // Submit the new row.
             wsSubmit.Execute();
          }
       }
       else
       {
          // Enumerate the existing contacts and see if 
          // any items have been changed or set to be deleted.
          while (xiContacts.MoveNext())
          {
             if (xiContacts.Current.SelectSingleNode(
                "@Changed", ns).Value == "true")
             {
                // Set the values in the Add List Item Template XML file
                // to the values in the updated row.
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='Title']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@Title").Value);
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='FirstName']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@FirstName").Value);
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='LastName']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@LastName").Value);
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='Phone']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@Phone").Value);
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='Email']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@Email").Value);
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='Changed']", ns)
                   .SetValue("false");
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='ID']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@ID").Value);
    
                // Set the value of the Cmd attribute to "Update".
                xnCAML.SelectSingleNode(
                   "/Batch/Method/@Cmd", ns)
                   .SetValue("Update");
    
                // Submit the updates for the current row.
                wsSubmit.Execute();
             }
             // If the Delete field is set to "true" for the current
             // row, in the Batch fragment set the ID for the row
             // and set the Cmd attribute to "Delete".
             if (xiContacts.Current.SelectSingleNode(
                "@Delete", ns).Value == "true")
             {
                xnCAML.SelectSingleNode(
                   "/Batch/Method/Field[@Name='ID']", ns)
                   .SetValue(xiContacts.Current.SelectSingleNode(
                   "@ID").Value);
                xnCAML.SelectSingleNode(
                   "/Batch/Method/@Cmd", ns)
                   .SetValue("Delete");
    
                // Submit the delete operation for the current row.
                wsSubmit.Execute();
             }
          }
       }
    
       // Create a DataConnection object for the MyContacts 
       // data connection.
       DataConnection dcContacts = this.DataConnections["MyContacts"];
    
       // Execute the data connection to refresh the list of 
       // contacts to reflect any additions, updates, or deletions.
       dcContacts.Execute();
    
       // Clear the values in the repeating table for 
       // adding new contracts.
       ClearEnteredValues(xnDoc);
    }
    
    catch (Exception ex)
    {
       MessageBox.Show("The following error occurred: " + ex.Message);
       throw;
    }
    
  7. Save your additions, build the code, and then switch back to InfoPath form design view.

Testing the Form

Now that everything is in place, you can preview the form to test it. Each time you make a change to the list from the form, you can confirm that the changes were submitted to the list by opening the list in a Web browser, making sure to refresh the page if it was opened before you submitted changes.

To test the form

  1. Click the Preview button to preview the form.

    If there are any items already in the list, they are displayed in the first repeating table control.

  2. Select the Add New Contacts? check box. This should display the second repeating table with a blank row for adding a new contact item.

  3. Fill in values for Title, FirstName, LastName, Email and Phone fields in the second repeating table control.

    NoteNote

    If you want, you can click Add New Contact below the first row to add more than one new contact at a time.

  4. Click the Submit Changes button.

    The contact information is submitted as one or more new items to the MyContacts list, which are then displayed in the first repeating table control that is bound to the list.

  5. In the first repeating table control, make a change to the values in one or more of the items in the list.

  6. Click the Submit Changes button.

    The updated contact information is submitted to the MyContacts list.

  7. In the first repeating table control, select the Delete? check box for one or more of the items in the list.

  8. Click the Submit Changes button.

  9. The items to delete are submitted to the MyContacts list, and the data connection is refreshed to update the items displayed in the control.

    Figure 2. Previewing the form

    Previewing the form

Next Steps

Because the form template contains code for updating list items, you must perform additional steps before you can deploy it, such as digitally signing the form template. For more information about deploying a form template that contains code, see How to: Deploy InfoPath Projects. If your users do not have InfoPath, but you do have Office SharePoint Server 2007 with InfoPath Forms Services or Office Forms Server 2007, you can deploy the form template to your server so that users that do not have InfoPath can open the form in the browser. Completing the deployment process for a form template that contains code requires administrator rights on the server. For information about how to deploy a form template that contains code to Office SharePoint Server 2007 or Office Forms Server 2007, see "Deploying Form Templates That Contain Code" in Developing and Deploying Form Templates for InfoPath Forms Services.

Conclusion

By connecting to the SharePoint Lists Web service and submitting data by using its UpdateListItems method, you can create an InfoPath solution for adding, updating, and deleting items in a SharePoint list. This article describes how to design a form template and write code to create such a solution.

NoteNote

You can also create a simpler codeless solution for submitting items to a SharePoint list from an InfoPath form. For more information, see Submitting to a SharePoint List on the InfoPath Team Blog.

Acknowledgments

I would like to thank Scott Heim for his contributions to this article.

Additional Resources