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:
- 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. - 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. - Double-click the Get Value button to open its Properties dialog box.
- On the Button Properties dialog box, click Edit Form Code to add a Clicked event handler for the button to the form template.
- 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 Basicwhere "/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.Dim fieldValue As String = MainDataSource.CreateNavigator().SelectSingleNode( _
"/my:myFields/my:field1", NamespaceManager).Value
Related InfoPath Articles:
- How to programmatically get or set the XHTML code of a Rich Text field in InfoPath 2007
- How to simulate Excel's VLOOKUP function in InfoPath to look up data in a secondary data source using rules and filters
- Programmatically retrieve the value of another field in the same row of a repeating table in InfoPath 2007
