When creating a InfoPath forms to collect business application data, it is often required to use an auto-increment (auto indexing) behavior for auto numbering different data in the form. This is a very common and useful when implementing a repeating table and/or repeating section in order to index the rows in the repeating table or the repeating sections, correspondingly.
In the following post I'll demonstrate three available options to archive this behavior without writing a single line of code!
This options are available and support by both, InfoPath 2003 and InfoPath 2007.
This post has a sample InfoPath form template – DOWNLOAD THE SAMPLE (Auto_Increment_Sample.zip).
Option 1 – Use an Expression Box with the XPath set to position()
|This option is great if all you want to do is show the row number. But if you actually want to store the sequential auto-increment numbering in a field, this is not a good option since Expression Box cannot update and save its data to fields in the form.
See option 1 in the attached Auto_Increment_Sample.xsn
Option 2 – Use count() of preceding-sibling
|To store the auto-number in the forms field, i.e Index_Count field in our form, use the following XPath formula as the default value of the Index_Count field: count(../preceding-sibling::*/my:Index_Count) + 1 and uncheck the update this value when the result of this formula is recalculated.
This XPath actually counts (count() function) the number of nodes in the same level above the current node (preceding-sibling statement).
This will do the work, but if we need the generated Index_Count to assure unique across the table rows, than this will not be enough, since it in case you delete a row and then insert another row, than will have two rows with the same Row_ID value.
See option 2 in the attached Auto_Increment_Sample.xsn
Option 3 – Use InfoPath Rule to create a counter mechanism
In this option we'll use an InfoPath Rule on the index field. This rule will use as a counter mechanism to increment a counter filed as follow:
1. A field to store the item count has been added – Item_Count (/my:myFields/my:Item_Count), with a default value of 1. This field will act as a global variable to the form instance and will hold the latest generated Index_Counter_Rule.
3. A rule named “Set_Item_Count” has been added to the Index_Counter_Rule field. This rule is will set the value of Item_Count to (Item_Count + 1). This rule is being triggered after the content of the field is being changed. When we add a new row, the content of this field is being changed due to the default value settings.
See option 3 in the attached Auto_Increment_Sample.xsn
Use the options above as you find best fit to your needs.