DotNet Development, SharePoint Customizing, Silverlight, MS Infrastructure and other tips and tricks

How to manipulate InfoPath with CodeBehind

Posted by PANVEGA on February 16, 2009

I wonna show you how easy it is to manipulate the InfoPath Formular in C# Codebehind. The compiled DLL becomes part of the InfoPath form template (XSN) file.

1. First you have to install the VSTA tools for Visual Studio.

With the familiar Visual Studio development environment, VSTA enables Visual Basic and Visual C# developers to easily build managed customizations for both COM and .NET applications. The VSTA SDK includes integration tools, samples, and documentation to help you get started with VSTA.

Download Visual Studio Tools for Applications (VSTA)  here

2. Then create in InfoPath a new Formular with some for instance textboxes and Submit buttons. Under Tool–> Programming –>Microsoft Visual StudioTools… you will automatically redirected to the VS CodeBehind InfoPath Project.

3. In addition the Tool deploys a dll in your XSN file when building the project.

4. e.g. create a new Button. In the properties under general choose under ations “Rules and Custom Code” –> Edit Form Code

5. The Tool create you a new Event. How to create an Event Handler?

public void InternalStartup()
//EventManager.FormEvents.ContextChanged += new ContextChangedEventHandler(FormEvents_ContextChanged);
((ButtonEvent)EventManager.ControlEvents[“CTRL2_5”]).Clicked += new ClickedEventHandler(CTRL2_5_Clicked);

6. here is the method for this event. Create a Navigator and Namespace.

public void CTRL2_5_Clicked(object sender, ClickedEventArgs e)
// Create an XPathNavigator to walk the main data source
// of the form.
XPathNavigator xnMyForm = this.CreateNavigator();
XmlNamespaceManager ns = this.NamespaceManager;

// Set the fields in the form.
xnMyForm.SelectSingleNode(“/my:myFields/my:name“, ns)
xnMyForm.SelectSingleNode(“/my:myFields/my:check“, ns)

// Clean up.
xnMyForm = null;


7. my:name is a textbox field with this given name and a simple checkbox

8. With SetValue() you can chane the current value. Here is the whole just edited formular in XML

<?xml version=”1.0″?><?mso-infoPathSolution solutionVersion=”″ productVersion=”12.0.0″  PIVersion=”″
\Microsoft\InfoPath\Designer2\4b64fbe91f7d4cf4\manifest.xsf” ?><?mso-application
progid=”InfoPath.Document” versionProgid=”InfoPath.Document.2″?>
<my:myFields xmlns:xsi=”;
xmlns:xd=”; xml:lang=”en-us”>



The Application object includes properties and methods that return references to the high-level objects of the InfoPath object model. For example, the XmlForms property returns a reference to a collection of XmlForm objects.

The Application object is the top-level object in the InfoPath object model, and it provides a number of properties and methods that can be used to access lower-level collections and objects in the object model, and to perform a variety of general purpose functions.

other Examples:

1. In the following example, the event handler for the Submit event is used to prevent the form from being submitted if the form has not been saved.

public void FormEvents_Submit(object sender, SubmitEventArgs e)
if(this.Dirty || this.New)
MessageBox.Show(“Please save this form before submitting it.”);
e.CancelableArgs.Cancel = true;
e.CancelableArgs.Message = “Submit succeeded.”;

2. Retrieve the rows of the repeating table:
XPathNavigator root = MainDataSource.CreateNavigator();
XPathNodeIterator rows = root.Select(
“/my:myFields/my:rows/my:row”, NamespaceManager);

// Loop through the rows of the repeating table
while (rows.MoveNext())

// Retrieve the SoftwareTitle

string Title= rows.Current.SelectSingleNode(“my:Title”, NamespaceManager).Value;


3. how to retreive and add a new Item to a custom SP List:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat(“<Method ID=\”{0}\” Cmd=\”New\”>”, id.ToString());
sb.AppendFormat(“<Field Name=\”Title\”>{0}</Field>”, title);

XmlDocument methodXML = new XmlDocument();

XPathNavigator batch = DataSources[“CustomListName“].CreateNavigator();
XPathNavigator batchNav = batch.SelectSingleNode(“/Batch”, NamespaceManager);

one more good Example:

There’s quite a bit of C# coding in the form, to retrieve information from active directory and submit repeating rows to the sharepoint list.

using System.DirectoryServices;

public void FormEvents_Loading(object sender, LoadingEventArgs e)
// Get the user name of the current user.
string userName = this.Application.User.UserName;

// Create a DirectorySearcher object using the user name
// as the LDAP search filter. If using a directory other
// than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher(
“(mailNickname=” + userName + “)”);

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.
if (result == null)
MessageBox.Show(“Error finding user: ” + userName);
// Create a DirectoryEntry object to retrieve the collection
// of attributes (properties) for the user.
DirectoryEntry employee = result.GetDirectoryEntry();

// Assign the specified properties to string variables.
string FullName = (employee.Properties[“displayName”].Value != null) ? employee.Properties[“displayName”].Value.ToString() : “”;
string Mail = (employee.Properties[“mail”].Value != null) ? employee.Properties[“mail”].Value.ToString() : “”;

// Create an XPathNavigator to walk the main data source of the form.
XPathNavigator xnMyForm = this.CreateNavigator();
XmlNamespaceManager ns = this.NamespaceManager;

// Set the fields in the form.
xnMyForm.SelectSingleNode(“/my:myFields/my:RequestorFullName”, ns)
xnMyForm.SelectSingleNode(“/my:myFields/my:RequestorEmail”, ns)

// Clean up.
xnMyForm = null;

catch (Exception ex)
MessageBox.Show(“The following error occurred: ” +


Note: When the form is deployed as a feature for a workflow. The managed code may not be executed. This issue occurs because a compiled DLL becomes part of the InfoPath form template (XSN) file when you create managed code behind an InfoPath form. Microsoft Office Forms Services does not extract a DLL by expanding the XSN file when the XSN file is installed by using the features functionality.


To resolve this issue, copy the compiled DLL to the same folder to which your feature XSN file was deployed.

More Informations:


2 Responses to “How to manipulate InfoPath with CodeBehind”

  1. Großartig Kollegen – da kann man weiterdenken

  2. I can imagine, that there’s more to say

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: