Passing a query string parameter to an InfoPath data source
Posted
Monday, July 14, 2008 2:01 PM
by
CoreyRoth
Recently, I wanted to create a simple InfoPath form that took a query string parameter (an id) and passed it to a secondary data source that called a web service. There may be a simpler solution to this, but I went with a programmatic solution. So, I set my preferred language as C# and went to the Programming menu item under the Tools menu. For the purpose of this example, my secondary data source is called WebServiceDataSource and it takes a single parameter called ProductId. Before you add any code, you will want to turn off the option to automatically execute the data source on form load.
This code goes in the FormEvents_Loading event handling method. The first thing we need to do is actually get the parameter passed in from the query string. This works similarly to TryParse. It returns true if successful and writes the value into an out parameter.
e.InputParameters.TryGetValue("ProductId", out productId)
This next line of code selects the node of the ProductId parameter and sets the value. XPath is used to find the current node. Remember you can get the XPath query of the node by selecting it in the Data Source explorer and using the Copy XPath context menu item.
DataSources["WebServiceDataSource"].CreateNavigator().SelectSingleNode("/dfs:myFields/dfs:queryFields/tns:WebServiceDataSource/tns:ProductId", NamespaceManager).SetValue(productId);
The last thing you need to do is execute the data source.
DataSources["WebServiceDataSource"].QueryConnection.Execute();
At this point you can pass a parameter to the form and your secondary data source will use that parameter. Since there is code in the form now, when you publish it you will of course have to select the Administrator-approved form template option. You will then have to upload it on the manage form templates page in Central Administration. Here is what all of the code looks like together.
string productId;
// get the value if it exists
if (e.InputParameters.TryGetValue("ProductId", out productId))
{
// select the node in the secondary datasource
DataSources["WebServiceDataSource"].CreateNavigator().SelectSingleNode("/dfs:myFields/dfs:queryFields/tns:WebServiceDataSource/tns:ProductId", NamespaceManager).SetValue(productId);
DataSources["WebServiceDataSource"].QueryConnection.Execute();
}
else
{
// handle an error
}
I am no expert on InfoPath, but this solution works for me. If you know of a better solution, please post it.