Monday, August 3, 2015

Get selected records on the grid / datasource

This should also be a common task for Dynamics AX developers.
Fortunately, there's a little helper class in AX to make it easier for us, the MultiSelectionHelper.
For example, if you want to get a set of selected records in a grid, you could use it like this:

MyTableBuffer              myTableBuffer;
MultiSelectionHelper      selectionHelper   = MultiSelectionHelper::construct();
Set                             selectedRecords  = new Set(Types::Record);

selectionHelper.parmDataSource(myTableBuffer_DS);

myTableBuffer = selectionHelper.getFirst();

while (myTableBuffer)
{
    selectedRecords.add(myTableBuffer);
     myTableBuffer = selectionHelper.getNext();

The code above should be very useful when getting the list of selected records directly on the form.
Another simplest way is
dataset.Columnname;
Eg.:
     MainAccount_ds is a dataset then  write like MainAccount.MainAccountId;
to get current selected row on the grid's Account Number.

if you want to get the selected records in a class that was called from a form, for example, you could use the MultiSelectionHelper like this:

public static void main(Args _args)
{   
    FormDataSource          formDataSource;   
    MyTableBuffer           myTableBuffer;
    FormRun                 caller = _args.caller();
    MultiSelectionHelper    helper = MultiSelectionHelper::createFromCaller(caller);
    Counter                 i;
    // First we need to get the correct form data source
    for (i = 1; i <= caller.dataSourceCount(); i++)
    {
        formDataSource = caller.dataSource(i);
         if (formDataSource.table() == tableNum(MyTableBuffer))
        {
            break;
        }
    }
    // We then tell the selection helper object to create ranges for the selected records
    helper.createQueryRanges(formDataSource.queryBuildDataSource(), fieldStr(MyTableBuffer, RecId));
    // Now we can traverse the selected records
    myTableBuffer = helper.getFirst();
     while (myTableBuffer)
    {
        info(myTableBuffer.RecId);
         myTableBuffer= helper.getNext();
    }
}

No comments:

Post a Comment