How To: Create An Auto-Number Field
How To: Create an Auto-Number Field
When designing an InfoPath form a form designer may need to create an auto-number field. This type of field provides a sequential set of numbers that is updated as new rows are added to a repeating table. In this example, I will show how to this can be done using InfoPath.
For an example, the following data source is used to capture first and last names within a form. As a new name is added, the ItemNumber field is updated to show the current number of entries. Additionally, if any rows are deleted the ItemNumber field is updated to reflect this change and decrement the existing values.

Once the above data source is dragged onto the InfoPath form and placed into a repeating table this looks like the following.

The following steps show how to design the remainder of the form so that the ItemNumber field is either incremented or decremented appropriately.
- Make the Item Number field read only. Although, not necessary this will ensure that users don’t accidentally update or change the field.

- Add the following value at the form level. This value is checked to protect against reentrant code.
var fInsideEnsure = false;
- Add the following function within the Script Editor. This function is called at various portions of the form and ensures that the ItemNumber field is correctly numbered.
// autonumber sets "ItemNumber" text to position of repeating section
function autonumber()
{
// protect from reentrancy from validation handlers
if (fInsideEnsure) return;
fInsideInsure = true;
// select nodes and initialize counter
var xmlNodes = XDocument.DOM.selectNodes("/my:myFields/my:NameList");
var iPos = 1;
// set counter for each row
for (var xmlNode = xmlNodes.nextNode(); xmlNode != null; xmlNode = xmlNodes.nextNode())
{
// set text of text node to position of an repeating section.
xmlNode.selectSingleNode("my:ItemNumber").text = iPos++;
}
fInisdeInsure = false;
}
- Add the following code to the forms’ OnLoad event. This event is fired when the form is loaded and calling the autonumber function ensures that the numbering sequence is correct.
function XDocument::OnLoad(eventObj)
{
// call autonumber
autonumber();
}
- Add the following code to the NameList groups’ OnAfterChange event. This ensures that the autonumber function is called and validates the function is called only when a row is added and ignores when changes are made to the various elements within the row.
function msoxd_my_NameList::OnAfterChange(eventObj)
{
// Write code here to restore the global state.
if (eventObj.IsUndoRedo)
{
// An undo or redo operation has occurred and the DOM is //read-only.
return;
}
if (eventObj.Site != eventObj.Source)
{
// Only re-number when a row has been deleted or added.
// always ignore when just the values of a //child nodes //change.
return;
}
// Renumber only after add/remove
autonumber();
}
I have included the sample form discussed here for download.