There are times when you connect to a secondary data source in InfoPath and would like to automatically populate a repeating table based off the source. This can be done whether it is through a database or SharePoint data connection.
First step would be to create a secondary data connection in InfoPath. Once you have done this, drag a repeating table onto your page. For my example, I placed the code in the loading event of the form.
The first section of code you need to set an XPathNodeIterator to specify the secondary data source that needs to be pulled from. In addition, the actual node where the repeating group resides needs to be specified. (See line 2)
Once the node iterator is set, then the loop of code that will set all the fields of the actual repeating table. An XML document needs to be created to store the values and then after all the elements are populated, it will be appended to the repeating table row and then looped through again as many times as there is data that exists in the data source. The first part of the xml document is called the group and that references the repeating table. The xml nodes marked field reference the repeating table fields. The InnerText needs to be set of the field nodes and this is obtained by the navigator created in the foreach loop. The field in that navigator is obtained from the secondary data source. (See lines 6-19)
After setting all the nodes with the proper values, the repeating table needs to be appended with the xml document. The group that hold the repeating table is referenced and the xml document is appended. (See line 22)
Final step is to remove the empty row in the repeating table. Create a navigator that references the FIRST item index of the repeating table and then call the DeleteSelf() method. (See lines 25-26)