Count the total amount of sections in a Repeating Section in InfoPath on insert or delete
Learn how to programmatically count the amount of sections in a repeating section control on an InfoPath form whenever a section is inserted or deleted.
Problem
You have a Repeating Section control in InfoPath and you want to programmatically count the total amount of sections that the Repeating Section contains whenever a section is inserted or deleted.
Solution
Use the Changed event of the repeating group node of the Repeating Section and the Count property of an XPathNodeIterator to programmatically count the amount of sections in a Repeating Section control on an InfoPath form.
Note: While you don't have to write code to count the amount of sections in a Repeating Section, you will have to do so if you want a running count (a total which is updated dynamically as sections are inserted or deleted) as demonstrated in this article.
Before You Begin
You should know how to do the following:
Discussion
In Programmatically execute code when a repeating table row is inserted or deleted I showed you how to add an event handler to a repeating group node of a Repeating Table. Because a Repeating Section is similar to a Repeating Table, you can apply the same concept to the group node of a Repeating Section control.
You can accomplish this functionality as follows:
- Follow the instructions in Programmatically execute code when a repeating table row is inserted or deleted, but use a Repeating Section control instead of a Repeating Table control.
- Add an extra Text Box control to the form template, name it runningCount, and set its Default Value to 1.
-
Add the following C# code to the Changed event handler of the group2 node:
XPathNavigator root = MainDataSource.CreateNavigator();
// Count the amount of sections whenever a section is inserted or deleted
if (e.Operation == XmlOperation.Insert || e.Operation == XmlOperation.Delete)
{
XPathNodeIterator iter = root.Select("//my:group2", NamespaceManager);
if (iter != null)
root.SelectSingleNode(
"//my:runningCount",
NamespaceManager).SetValue(iter.Count.ToString());
}
Or add the following Visual Basic code to the Changed event handler of the group2 node:
Dim root As XPathNavigator = MainDataSource.CreateNavigator()
' Count the amount of sections whenever a section is inserted or deleted
If e.Operation = XmlOperation.Insert Or e.Operation = XmlOperation.Delete Then
Dim iter As XPathNodeIterator = root.Select("//my:group2", NamespaceManager)
If iter IsNot Nothing Then
root.SelectSingleNode( _
"//my:runningCount", _
NamespaceManager).SetValue(iter.Count.ToString())
End If
End If
You should now have a fully functional form so that whenever you insert or delete a section, the runningCount field is updated with the total amount of sections that the Repeating Section contains.
Related InfoPath Articles:
