Submitting Data from InfoPath 2007 to a SharePoint List
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:
-
Create the SharePoint list.
-
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.
-
Create the form template and add the required data connections.
-
Identify the GUID used as the ID for the list.
-
Add controls to the form template to display the current items in the list.
-
Add fields and controls for entering new items to submit to the list.
-
Add a connection to the SharePoint Lists Web service and define the parameters for calling the UpdateListItems Web method.
-
Add the event handler code required to submit additions, updates, and deletions from the list.
-
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-
On the Site Actions menu, click Create.
-
On the Create page, click Custom List.
-
Name the list MyContacts, and then click Create.
-
On the Settings menu, click List Settings.
-
In the Columns section, click Create Column.
-
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 |
|
|
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-
Start Notepad (or any text editor).
-
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>
-
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-
Start Office InfoPath 2007.
-
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.)
-
In the Based on list, click Blank, clear the Enable browser-compatible features only check box, and then click OK.
-
On the Tools menu, click Data Connections, and then click Add.
-
In the Data Connection Wizard dialog box, click Create a new connection to, click Receive data, and then click Next.
-
Click XML document, and then click Next.
-
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.
-
Click the Include the data as a resource file in the form template or template part, and then click Next.
-
Ensure that the Automatically retrieve data when the form is opened check box is selected, and then click Finish.
-
In the Data Connections dialog box, click Add.
-
Click Create a new connection to, click Receive data, and then click Next.
-
Click SharePoint library or list, and then click Next.
-
Type the URL to the MyContacts list that you created in the "To create the SharePoint list" procedure, and then click Next.
-
In the Select a list or library list, select MyContacts, and then click Next.
-
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.
-
Make sure that the Automatically retrieve data when the form is opened check box is selected, and then click Finish.
-
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-
Open a browser and navigate to the MyContacts list.
-
On the Settings menu, click List Settings.
-
In the browser’s address bar, you will see the URL appended with
List= -
Copy everything after the equal sign and paste this into a text editor because you will need this value later.
Important: The list GUID must be formatted as: {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. If the list GUID has the hyphens and braces escaped (with%7Bfor the opening brace,%2Dfor the hyphens, and%7Dfor 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-
Open the Data Source task pane.
-
In the Data Source drop-down list, click the MyContacts (Secondary) connection.
-
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.
-
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.
-
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?
-
Select the Delete? column heading, and then click the Center button on the Formatting tool bar.
-
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-
In the Data Source drop-down list, click Main.
-
In the Data Source pane, right-click the myFields folder, and then click Add.
-
Add a True/False field named AddContacts, set the Default Value to FALSE, and then click OK.
-
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.
-
Change the label of the AddContacts check box to read Add New Contacts?
-
Right-click the myFields folder, and then click Add.
-
Add a Group named gpContacts.
-
Right-click the gpContacts folder, and then click Add.
-
Add a Group named gpContact, select the Repeating check box, and then click OK.
-
Right-click the gpContact folder, and then click Add.
-
Add five Text fields named Title, FirstName, LastName, Email, and Phone.
-
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.
-
Right-click the Section control that you added in step 12, and then click Conditional Formatting.
-
In the Conditional Formatting dialog box, click Add.
-
Under If this condition is true, set the condition to AddContacts is equal to FALSE.
-
Under Then apply this formatting, click Hide this control.
-
Click OK twice.
-
Right-click the Repeating Table control that you added in step 12, and then click Repeating Table Properties.
-
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.
-
Right-click the myFields folder, click Add, and then add a Text field named ListName.
-
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-
Click above the two Repeating Table controls that you added in the earlier procedures.
-
On the Table menu, point to Insert, and then click Layout Table.
-
Set the Number of columns to 1 and set the Number of rows to 2, and then click OK.
-
Right-click the topmost Repeating Table control, click Cut, and then paste it into the first row of the layout table.
-
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.
-
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.
-
Right-click the title row of the topmost Repeating Table control, point to Insert, and then click Rows Above.
-
Select all of the cells in the new row, right-click the selected cells, and then click Merge Cells.
-
Type Current contacts in the list: in the new row.
-
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
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: |
|---|
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
|
-
On the Tools menu, click Data Connections, and then click Add.
-
In the Data Connection Wizard dialog box, click Create a new connection to, click Submit data, and then click Next.
-
Click To a Web service, and then click Next.
-
Type the URL to the Lists Web service (see previous note), and then click Next.
-
In the Select an operation list, select the UpdateListItems operation, and then click Next.
-
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.
-
Double-click the tns:updates parameter name, select the Add List Item Template (Secondary) data source, select the Batch folder, and then click OK.
-
In the Include drop-down list, select XML subtree, including selected element, and then click Next.
-
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-
Right-click the check box that is bound to the AddContacts field, point to Programming, and then click Changed Event.
-
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; }
-
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; } }
-
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-
Right-click the header row of the repeating table bound to the MyContacts group, point to Programming, and then click Changed Event.
-
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; }
-
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-
In the Design Tasks task pane, click Controls.
-
Drag a Button control below the second repeating table.
-
Double-click the button to display its properties dialog box.
-
On the General tab of the Button Properties dialog box, change the Label property to Submit Changes, and change the ID property to btnSendChanges.
-
Click Edit Form Code to open the code editor.
-
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; }
-
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-
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.
-
Select the Add New Contacts? check box. This should display the second repeating table with a blank row for adding a new contact item.
-
Fill in values for Title, FirstName, LastName, Email and Phone fields in the second repeating table control.
Note: If you want, you can click Add New Contact below the first row to add more than one new contact at a time. -
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.
-
In the first repeating table control, make a change to the values in one or more of the items in the list.
-
Click the Submit Changes button.
The updated contact information is submitted to the MyContacts list.
-
In the first repeating table control, select the Delete? check box for one or more of the items in the list.
-
Click the Submit Changes button.
-
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
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.
Note: |
|---|
| 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
-
InfoPath Developer Portal
Information about InfoPath developer resources.
-
InfoPath Developer Reference for Managed Code
Overviews, programming tasks, and class library reference information to help you build Office InfoPath 2007 form templates that contain business logic written in Microsoft Visual Basic or Microsoft Visual C#.
-
Microsoft Office Online InfoPath Home Page
Office Online site that provides information about InfoPath form design, declarative logic, and other features that are available through the InfoPath user interface.
This functionality is key, I can't see how they haven't known that everyone would want to get the repeating data into a table. What good is the data stuck only in the form???
Please MS find a way to build the functionality into InfoPath to submit to multiple SharePoint lists, including repeating control data! This is highly needed.
Thanks!
- 12/3/2011
- Daniel_DeHaven
Thanks.
- 8/10/2011
- C Flips
InfoPath cannot submit the form.
An error occurred while the form was being submitted.
The SOAP response indicates that an error occurred on the server:
Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
<detail><errorstring xmlns="Value'>http://schemas.microsoft.com/sharepoint/soap/">Value does not fall within the expected range.</errorstring></detail>
This leads me to believe there is something wrong with the submission data connection or the Add List Item Template.xml file. I double checked the xml file against some general working with SharePoint services code and it looks fine. No clue what I'm doing wrong. I'd love to see a functioning project.
- 6/17/2011
- Chris Wilkins
I can change the contents of existing data, but cannot populate an empty field.
If I delete the contents of a column from a row and update the list, the changes are called in but now I cannot update that column as it is now empty.
This functionality is crucial for something I am working on at the moment, where I need users to batch update items in a list, but the columns are initially blank.
Any advice would be welcome!
- 5/20/2011
- richduffy
- 4/20/2011
- Digambar J Kashid
I did everything the article said, but I wanted to publish it using Forms Services and this is the error?
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.Office.InfoPath.Server.SolutionLifetime.WebServiceHelper.GetResponseHelper(WebRequest request, DataAdapterTimer dataAdapterTimer, DataAdapterCredentials credentials, Stopwatch timer, ExecWebRequestExceptionState state, String adapterName, Boolean isQuery)
at Microsoft.Office.InfoPath.Server.SolutionLifetime.WebServiceHelper.ExecWebRequestSync(XPathNavigator inputSubDOM, Boolean[] inputUseDataset, XPathNavigator resultsSubDOM, Boolean resultUseDataset, XPathNavigator errorsSubDOM, Uri serviceUrl, Uri soapAction, Int64 timeOutMillisec, Solution solution, Document document, String name, Boolean isQuery, DataAdapterTimer dataAdapterTimer, DataAdapterCredentials credentials, Boolean useDcl, Boolean useProxy, Boolean useSelf)
Can you help me?
- 3/28/2011
- calvaradog
If I click ok and carry on the Repeating Table appears, I can add new records ok, delete records, update records without any problem. I only get an error when using the check box, which I find quite odd, as it is only a copy and paste exercise from the supplied code. Has any one else had this problem?
- 12/21/2010
- richduffy
- 9/6/2010
- Devubha
http://www.developerfusion.com/tools/convert/csharp-to-vb/
- 7/14/2010
- CoryatWork
- 7/14/2010
- CoryatWork
This language is not supported or no code example is available.Please help me find the VB code for this tutorial... any help would be greatly appreciated.
Thank you.
It doesn't seem to matter which language I choose.
- 6/21/2010
- McGrathj
I am getting the following error while submitting data.
System.Runtime.InteropServices.COMException
An item with the following index does not exist in the collection: Add List Item Template
at Microsoft.Office.Interop.InfoPath.SemiTrust.DataObjects.get_Item(Object varIndex)
at Microsoft.Office.Interop.InfoPath.SemiTrust.DataObjectsCollectionWrapper.get_Item(Object varIndex)
at Microsoft.Office.InfoPath.Internal.DataSourcesHost.get_Item(String name)
at List_Data.FormCode.btnSendChanges_Clicked(Object sender, ClickedEventArgs e)
at Microsoft.Office.InfoPath.Internal.ButtonEventHost.OnButtonClick(DocActionEvent pEvent)
at Microsoft.Office.Interop.InfoPath.SemiTrust._ButtonEventSink_SinkHelper.OnClick(DocActionEvent pEvent)
Please Help me reagrding this.
Thanks,
Kumar.
- 6/9/2010
- apkumar
I have a problem. I followed the tutorial and add a custom list in SharePoint. The first problem: Using a Custom List doesn't work. I have to use a data connection library. After adding the rows in the list, I load the XML-File into InfoPath. After that, I would build the connection to the new Sharepoint-List. I can choose the list, but I can't see the rows and InfoPath said, that there are no data connection files at this place.
Can somebody tell me, what it's wrong?
Greetings,
Karon
- 3/11/2010
- Karon1981
Does anyone know of a way to get at the value of the new list item ID that was created?
- 2/23/2010
- pikes1654
On my DataSource dsCAML = this.DataSources["Add List Item Template"]; is throwing COMException was unhandled by user code
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 11/4/2009
- MisterAndersen
- 11/23/2009
- Thomas Lee
I did all rows wiht out any error and i compile my c# code with out any error but at end of execute there isn't any new row in my list and compiler didn't catch any error.
Can some body help me.
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 4/21/2009
- Amir sameni
- 11/23/2009
- Thomas Lee
I have published, verified, uploaded and activated the forms on my sharepoint server according to (http://msdn.microsoft.com/en-us/library/ms772110.aspx)
When I try to Submit the change I have this error :
"There has been an error while processing the form - An entry has been added to the Windows event log of the server. Log ID:5337"
In my 12 logs I found this :
03/23/2009 17:36:34.69 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Runtime 0 Medium Regenerating object: ProcessId:[9] CacheId: SiteFeatures_91ffb6e0-6a12-421e-92c0-c003f842ebc6
03/23/2009 17:36:38.49 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Runtime - Busine 82g6 Warning Business logic failed due to an exception. (User: DOMAIN\User, Form Name: ContactListToUpload, IP: , Request: http://mysharepointsite/_layouts/Postback.FormServer.aspx, Form ID: urn:schemas-microsoft-com:office:infopath:ContactListToUpload:-myXSD-2009-03-23T11-21-23, Type: NullReferenceException, Exception Message: La référence d'objet n'est pas définie à une instance d'un objet.) 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:38.50 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Object Model 7tge Assert Exception thrown from business logic event listener StackTrace: à Microsoft.Office.InfoPath.Server.DocumentLifetime.OMExceptionManager.CallFormCodeWithExceptionHandling(UserMessages userMessages, OMCall d) à Microsoft.Office.InfoPath.Server.SolutionLifetime.ButtonFormCode.<>c__DisplayClass2.<Click>b__0() à Microsoft.Office.InfoPath.Server.SolutionLifetime.ButtonFormCode.Click(Document document, XPathNavigator container) à Microsoft.Office.InfoPath.Server.DocumentLifetime.EventClick.Play(Document document, BindingServices bindingServices, EventLogProcessor eventLogProcessor) à Microsoft.Office.InfoPath.Server.DocumentLifetime.Event.PlayEvent(Document document, BindingServices bindingServices, EventLogProcessor eventLogProcessor) à Microsoft.Office.InfoPath.Server.Docum... 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:38.50* w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Object Model 7tge Assert ...entLifetime.EventLogProcessor.<>c__DisplayClass1.<ExecuteLog>b__0() à Microsoft.Office.InfoPath.Server.DocumentLifetime.EventLogProcessor.ExecuteLog(Int32 expectedEventLogID) à Microsoft.Office.InfoPath.Server.Docum 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:40.17 w3wp.exe (0x0AA4) 0x0FF4 SharePoint Portal Server Runtime 8gp7 Medium Topology cache updated. (AppDomain: /LM/W3SVC/1916344843/ROOT-1-128822862474298504)
03/23/2009 17:36:46.41 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Runtime - Busine 82g6 Warning Business logic failed due to an exception. (User: DOMAIN\User, Form Name: ContactListToUpload, IP: , Request: http://mysharepointsite/_layouts/Postback.FormServer.aspx, Form ID: urn:schemas-microsoft-com:office:infopath:ContactListToUpload:-myXSD-2009-03-23T11-21-23, Type: NullReferenceException, Exception Message: La référence d'objet n'est pas définie à une instance d'un objet.) 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:46.41 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Object Model 7tge Assert Exception thrown from business logic event listener StackTrace: à Microsoft.Office.InfoPath.Server.DocumentLifetime.OMExceptionManager.CallFormCodeWithExceptionHandling(UserMessages userMessages, OMCall d) à Microsoft.Office.InfoPath.Server.SolutionLifetime.XmlEventExternal.FireChangedEvent(XPathNavigator sender, XmlEventArgsHost args, Document document) à Microsoft.Office.InfoPath.Server.DocumentLifetime.XmlNotificationManager.<>c__DisplayClass6.<FireEventHelper>b__5() à Microsoft.Office.InfoPath.Server.DocumentLifetime.XmlNotificationManager.FireEventHelper(XPathNavigator nodeChanged, SortedList notifiers, XmlEventType eventType, Boolean internalListenersOnly) à Microsoft.Office.InfoPath.Server.DocumentLifetime.XmlNotificationManager.FireChangedEvents(XPathNavigator nod... 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:46.41* w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Object Model 7tge Assert ...eChanged, SortedList notifiers) à Microsoft.Office.InfoPath.Server.DocumentLifetime.XmlNotificationManager.<>c__DisplayClass3.<FireEventsToListeners>b__0() à Microsoft.Office.InfoPath.Server.DocumentLifetime.XmlNoti 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:46.41 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Runtime - Busine 82g6 Warning Business logic failed due to an exception. (User: DOMAIN\User, Form Name: ContactListToUpload, IP: , Request: http://mysharepointsite/_layouts/Postback.FormServer.aspx, Form ID: urn:schemas-microsoft-com:office:infopath:ContactListToUpload:-myXSD-2009-03-23T11-21-23, Type: NullReferenceException, Exception Message: La référence d'objet n'est pas définie à une instance d'un objet.) 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:46.41 w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Object Model 7tge Assert Exception thrown from business logic event listener StackTrace: à Microsoft.Office.InfoPath.Server.DocumentLifetime.OMExceptionManager.CallFormCodeWithExceptionHandling(UserMessages userMessages, OMCall d) à Microsoft.Office.InfoPath.Server.SolutionLifetime.ButtonFormCode.<>c__DisplayClass2.<Click>b__0() à Microsoft.Office.InfoPath.Server.SolutionLifetime.ButtonFormCode.Click(Document document, XPathNavigator container) à Microsoft.Office.InfoPath.Server.DocumentLifetime.EventClick.Play(Document document, BindingServices bindingServices, EventLogProcessor eventLogProcessor) à Microsoft.Office.InfoPath.Server.DocumentLifetime.Event.PlayEvent(Document document, BindingServices bindingServices, EventLogProcessor eventLogProcessor) à Microsoft.Office.InfoPath.Server.Docum... 110062d1-4b6a-4488-9098-f30c265476f0
03/23/2009 17:36:46.41* w3wp.exe (0x0AA4) 0x0FF4 Forms Server Forms Services Object Model 7tge Assert ...entLifetime.EventLogProcessor.<>c__DisplayClass1.<ExecuteLog>b__0() à Microsoft.Office.InfoPath.Server.DocumentLifetime.EventLogProcessor.ExecuteLog(Int32 expectedEventLogID) à Microsoft.Office.InfoPath.Server.Docum 110062d1-4b6a-4488-9098-f30c265476f0
Thanks for your help
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 3/23/2009
- BougRun
- 11/23/2009
- Thomas Lee
- 3/2/2009
- Sahoong
- 11/23/2009
- Thomas Lee
Pls forgive me for my poor english.
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 2/11/2009
- Manoj Kumar P
- 11/23/2009
- Thomas Lee
Has anyone else experienced this type of error? Occurs on adding new records to the list. Thanks in advance for any and all help!
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 12/29/2008
- Patrick Finnicum
- 11/23/2009
- Thomas Lee
Is there some reference information on using Windows forms in InfoPath? Is it possible to display windows forms in a browser version of InfoPath?
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 10/27/2008
- dslaby
- 11/23/2009
- Thomas Lee
In above example list of contacts are displayed in Infopath 2007 Page along with one check box
for delete functionality.
In the same functionality for Browser Enable Infopath 2007form ,
how to provide confirm message "Are you sure you want to delete?"
If user click on Ok then it will delete the item and if clicked on cancel it will not do any thing.
Is there any solution for this issue?
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 9/9/2008
- Mukesh K S
- 11/23/2009
- Thomas Lee
The overall information here is excellent and could be very useful, except that I consistently get an error when attempting to build the code. VSTA reports "The name 'MessageBox' does not occur in the current context. InfoPath Forms Service does not allow me to reference System.Windows.Forms, so I had to comment out the try and catch lines of the code. Is there a solution to this problem?
[tfl - 23 11 09] Hi - and thanks for your post. You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn or the MSDN Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quicker response using the forums than through the Community Content. For specific help about:
Visual Studio : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.vstudio%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
.NET Framework : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.dotnet.framework
PowerShell : http://groups.google.com/group/microsoft.public.windows.powershell/topics?pli=1
All Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 3/25/2008
- ChrisP123
- 11/23/2009
- Thomas Lee
- 9/29/2009
- mckinnej
1. When you create the list on SharePoint, the column name is very important. Use Camel Case for example FirstName is guaranteed to work
2. If you want to create a "Multiple lines of text" column, choose "Plain Text". Then in the Infopath form, you can use a "Rich Text Box" for this column
3. There is a length limit for column name (eventhough I am not sure what is the max character). You still can create the column in SharePoint, but when you submit the form, it will create nothing in the list. Column name example: ThisIsTheExampleForLongColumnName
4. To get GUID easier without doing any convertion, in the SharePoint list setting, click on Column Ordering and then either click OK or Cancel will do. You will see the GUID in the format you need now on the address linkbar.
5. If you have created a column in SharePoint, and you realize that this column name has problem, DO NOT EVER use this column again. Renaming wont fix it, but delete it and recreate it will fix it.
Now I am still struggling to get the Update existing list item from InfoPath. Somehow setting the CAML CMD="Update" wont do it. Even though I have put the same "ID". And have done some research. Most of them said that I have to use on_changed event handler (programming). But from the C# codes in this page, it looks like just setting the CMD in CAML to "Update" and use the same "ID" for list item will solve my problem. Just not working in my case. Anyone can give me some hint? Thanks
- 6/8/2009
- Yasin Lyyas
ChrisP123: The code examples do assume that you're opening the form in the InfoPath client. As you've discovered, System.Windows.Forms.MessageBox() is not supported for forms that can open in the browser. To display an error message in a web-based form on InfoPath Forms Services, you'd need to display the message in-line in the form itself.
One way to do that, is to add a text field to the Main data source, eg named "ErrorMsg", drag that as a Text Box control on to the form, and then use code like the following in the try/catch block to write the error message to the ErrorMsg field:
catch (Exception ex)
{
XmlNamespaceManager ns = this.NamespaceManager;
XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();
xnDoc.SelectSingleNode("/my:myFields/my:ErrorMsg", ns).SetValue(
"The following error occurred: " + ex.Message);
throw;
}
- 9/17/2008
- MarkRoberts
- 4/19/2009
- Stanley Roark
- 11/11/2008
- swp3000gt
Hello ChrisP123,
The other way around this is to add a reference to System.Windows.Forms and then add "Imports System.windows.forms" (VB) or "Using System.Windows.Forms" (C#).
Following the above, you can then use messagebox.show("Blah Blah Blah....")' in your code.
It worked for me.
cheers
- 10/8/2008
- WebNoel
