
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:
- Using a while loop
- 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
localSalesLineof typeSalesLine. - Initialize the variable: Assign the first record from the data source using
getFirst(). - Check for records: The
ifstatement ensures that there is at least one record to process. - Loop through records: The
whileloop continues as long aslocalSalesLineis not null. - Perform actions: Inside the loop, replace
// Do your thingwith the code you want to execute for each record. - Move to the next record: Update
localSalesLinewith the next record usinggetNext().
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
localSalesLinewithout initializing it immediately. - Initialize in the loop: In the
forloop’s initialization section, we assignlocalSalesLinethe first record. The ternary operator checks ifgetFirst()returns a record; if not, it usessalesLine_ds.cursor(). - Loop condition: The loop continues as long as
localSalesLineis not null. - Perform actions: Inside the loop, insert the code to be executed for each record where
// Do your thingis commented. - Move to the next record: After each iteration,
localSalesLineis updated with the next record usinggetNext().
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