Programmatically prevent users from adding more rows to a repeating table in InfoPath
Learn how you can use the Changed event of a repeating node and the DeleteSelf() method to programmatically prevent a user from adding more rows to a repeating table in InfoPath when the repeating table already contains a certain amount of rows.
Problem
You have a Repeating Table on an InfoPath form and when the Repeating Table already contains 3 rows, you want to prevent users from adding more rows to the it.
Solution
Use the Changed event of the repeating group node of the Repeating Table and the DeleteSelf() method of the Site object to programmatically prevent more rows from being added to a Repeating Table control on an InfoPath form.
Note:
A repeating node has only 2 events available:
- Changed event
- Validating event
The MSDN documentation says that neither the Changed event nor the Validating event allows users to cancel an operation, so you will have to find workarounds (as described in this article) if you want to cancel or undo operations performed on the rows or sections of a repeating node, that is, when inserting or deleting rows or sections.
Discussion
You can accomplish this functionality as follows:
- Follow the instructions in Programmatically execute code when a repeating table row is inserted or deleted
-
Add the following C# code to the Changed event handler of the group2 node:
if (e.Operation == XmlOperation.Insert)
{
// Get a reference to the Main data source
XPathNavigator domNav = MainDataSource.CreateNavigator();
// Count the amount of rows (group2 nodes). If there are
// more than 3 rows, delete the current row, which is the
// last row that was added
XPathNodeIterator iter = domNav.Select(
"//my:group2", NamespaceManager);
if (iter.Count > 3)
e.Site.DeleteSelf();
}
Or add the following Visual Basic code to the Changed event handler of the group2 node:
If e.Operation = XmlOperation.Insert Then
' Get a reference to the Main data source
Dim domNav As XPathNavigator = MainDataSource.CreateNavigator()
' Count the amount of rows (group2 nodes). If there are
' more than 3 rows, delete the current row, which is the
' last row that was added
Dim iter As XPathNodeIterator = domNav.Select( _
"//my:group2", NamespaceManager)
If iter.Count > 3 Then
e.Site.DeleteSelf()
End If
End If
You should now have a fully functional form so that if you have already added 3 rows to the repeating table, you will not be able to insert another row to the repeating table.
Related InfoPath Articles:
