Programmatically retrieve the value of an InfoPath form field using .NET code

Use the Copy XPath functionality to find out what the XPath expression of the field is and the Value property of the XPathNavigator object to retrieve the value of the field.

Problem

You have a field on an InfoPath form for which you would like to use code to retrieve its value.

Solution

Use the Copy XPath functionality to find out what the XPath expression of the field is and the Value property of the XPathNavigator object to retrieve the value of the field.

Discussion

You can accomplish the functionality as follows:

  1. Design an InfoPath form template as shown in figure 1.

    Figure 1. The InfoPath form template in design mode.

    with a Main data source that resembles the following figure:


    Figure 2. The Main data source of the form template.
  2. On the Data Source task pane, right-click field1 and select Copy XPath from the context menu.

    Figure 3. Copying the XPath for a form field to the clipboard.
  3. Double-click the Get Value button to open its Properties dialog box.
  4. On the Button Properties dialog box, click Edit Form Code to add a Clicked event handler for the button to the form template.
  5. Add the following code to the Clicked event handler you just added:
    C#
    string fieldValue = MainDataSource.CreateNavigator().SelectSingleNode(
    "/my:myFields/my:field1", NamespaceManager).Value;

    Visual Basic
    Dim fieldValue As String = MainDataSource.CreateNavigator().SelectSingleNode( _
    "/my:myFields/my:field1", NamespaceManager).Value
    where "/my:myFields/my:field1" is the XPath expression you copied using Copy XPath. After you use Copy XPath, you can just paste the XPath expression into your code.
 
 Subscribe for updates via RSS or Email

Related InfoPath Articles:

Copyright: This article may not be used on web sites (whether personal or otherwise), copied, disseminated, altered, printed, published, broadcasted, or reproduced in any way without an expressed written consent of S.Y.M. Wong-A-Ton. The techniques demonstrated in this article may be used within any Microsoft InfoPath project. This article is provided without any warranties. Copyright for this article is non-transferrable and remains with the author, S.Y.M. Wong-A-Ton.

InfoPath 2013 Cookbook: 121 Codeless Recipes for Beginners

InfoPath 2010 Cookbook: 101 Codeless Recipes for Beginners

InfoPath 2010 Cookbook 2: 101 Codeless Recipes for SharePoint 2010

InfoPath 2010 Cookbook 3: 101 Code Recipes for C# Developers

InfoPath 2010 Cookbook 4: 101 Code Recipes for VB Developers

InfoPath 2010 Cookbook 5: Integrating InfoPath with Excel and Excel Services