Although it sound simple, I had a really hard time finding the solution to delete multiple records in datagrid in one of my projects. I was using
XMLListCollection as a dataprovider and a single record could be deleted with
removeItemAt(index) method. However, for the multiple selection, Flex stores the indices of the selected rows in an array. If I iterate through these indices and start removing item using the index, as soon as the first record is removed, XMLListCollection re-arrange itself and remaining items get the new index which is not valid against the existing indices in the array. Also, there is no way that we can find if the row is selected just by iterating through the collection of rows. The frustrating part was that Google was not able to provide any answer.
So, after spending few hours with couple of failed attempts, something suddenly came to my mind. What-if I start removing item from the bottom of the collection, instead from the top. This will not change the indices of existing items. This worked for items selected in an order. However, if I select items in the datagrid randomly, it fails. Flex pushes the indices of the items to an array as they are selected. That means the indices are not in order. So, there is a method
Array.sort() to sort an array. Also, this method accept
sortOption to consider the values in the array as numeric. Finally it worked. Below is the sample code;
//get the selected indices in the array
var sIndices:Array = myGrid.selectedIndices;
//since the indices are pushed as they selected, we need to sort them in ascending order
sIndices.sort(Array.NUMERIC);
//get the highest index first and remove the item
// i.e. start removing items from the bottom so that change in index won't give any problem
for(var index:int = sIndices.length-1; index>=0; index--)
xmlListCollection.removeItemAt(sIndices[index]);
|
What amazed me the most is that I didn't find a single discussion in any of the websites, forums, blogs about this. Is it only me who want to have this kind of feature in the datagrid or the solution was so simple that people easily implemented it? :-)