AX / D365FO – Loop Through All Grid Records of a Data Source Form

In Microsoft Dynamics AX and Dynamics 365 for Finance and Operations (D365FO), there are times when you need to iterate over all the records displayed in a form’s grid. This could be for bulk updates, validations, or computations that need to be applied to each record individually.

In this article, we’ll explore two methods to loop through all grid records of a data source form:

  1. Using a while loop
  2. Using a for loop

Using a While Loop

The while loop is a straightforward way to traverse records until a certain condition is met. Here’s how you can implement it:

SalesLine localSalesLine;
localSalesLine  = salesLine_ds.getFirst() as SalesLine;

if (localSalesLine)
{
    while (localSalesLine)
    {
        // Do your thing
        localSalesLine = salesLine_ds.getNext() as SalesLine;
    }
}

Explanation:

  • Declare a variable: We start by declaring localSalesLine of type SalesLine.
  • Initialize the variable: Assign the first record from the data source using getFirst().
  • Check for records: The if statement ensures that there is at least one record to process.
  • Loop through records: The while loop continues as long as localSalesLine is not null.
  • Perform actions: Inside the loop, replace // Do your thing with the code you want to execute for each record.
  • Move to the next record: Update localSalesLine with the next record using getNext().

Using a For Loop

The for loop provides a concise way to iterate over records with initialization, condition, and increment/decrement in one line. Here’s the implementation:

SalesLine localSalesLine;

for (localSalesLine = salesLine_ds.getFirst() ? salesLine_ds.getFirst(true) : salesLine_ds.cursor();
     localSalesLine;
     localSalesLine = salesLine_ds.getNext())
{       
     // Do your thing
}

Explanation:

  • Declare a variable: We declare localSalesLine without initializing it immediately.
  • Initialize in the loop: In the for loop’s initialization section, we assign localSalesLine the first record. The ternary operator checks if getFirst() returns a record; if not, it uses salesLine_ds.cursor().
  • Loop condition: The loop continues as long as localSalesLine is not null.
  • Perform actions: Inside the loop, insert the code to be executed for each record where // Do your thing is commented.
  • Move to the next record: After each iteration, localSalesLine is updated with the next record using getNext().

Conclusion

Both the while loop and the for loop effectively allow you to iterate through all the records in a grid’s data source. The choice between them depends on your personal preference or specific coding standards within your project.

Remember to replace the placeholder comment // Do your thing with the actual operations you need to perform on each record.

Leave a comment