Programmatically add a row to a repeating table using an XmlWriter object
Use the XmlWriter object that is returned by the AppendChild method of the XPathNavigator object to add a row to a repeating table.
Scenario
You want to programmatically add a row to a repeating table by clicking a button.
Solution
Use the XmlWriter object that is returned by the AppendChild method of the XPathNavigator object to add a row to a repeating table.
Discussion
The AppendChild method has 4 overloads, one of which returns an XmlWriter object that you can use to create a row in a repeating table.
Before you can get started with writing code for InfoPath form templates, you have to have your programming environment correctly set up and be able to write C# or Visual Basic .NET code. See the following articles for information on what you must have installed before beginning to write code:
- Introduction to InfoPath programming environments
- More than one way to write code: Visual Studio and InfoPath
- Change the programming language of a form template
Once you've got your programming environment set up, 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. - Double-click the Add Row 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 of the button:
C#string myNamespace = NamespaceManager.LookupNamespace("my");
using (XmlWriter writer = MainDataSource.CreateNavigator().SelectSingleNode(
"/my:myFields/my:group1", NamespaceManager).AppendChild())
{
writer.WriteStartElement("group2", myNamespace);
writer.WriteElementString("field1", myNamespace, "Cell 1");
writer.WriteElementString("field2", myNamespace, "Cell 2");
writer.WriteElementString("field3", myNamespace, "Cell 3");
writer.WriteEndElement();
writer.Close();
}
Visual BasicDim myNamespace As String = NamespaceManager.LookupNamespace("my")
Using writer As XmlWriter = MainDataSource.CreateNavigator().SelectSingleNode( _
"/my:myFields/my:group1", NamespaceManager).AppendChild()
writer.WriteStartElement("group2", myNamespace)
writer.WriteElementString("field1", myNamespace, "Cell 1")
writer.WriteElementString("field2", myNamespace, "Cell 2")
writer.WriteElementString("field3", myNamespace, "Cell 3")
writer.WriteEndElement()
writer.Close()
End Using
- Save, build, and test your work.
Related InfoPath Articles:
