Move rows up and down in DataGrid / List AS3

If you create two buttons, ‘itemUpBtn’ and ‘itemDownBtn’, and a datagrid of name ‘itemGrid’, with a column of ID’s in it, you can move items up and down using this code. Fairly user friendly, as it re-selects the moved item once it’s moved (just relies on that ID column to move them around).

Below is the mouseclick handler function.

private function clickHandler(e:MouseEvent):void 
{
switch (e.target)
{
case itemUpBtn:
if (itemGrid.selectedItem) {
if(itemGrid.selectedItem.ID != 0) {
var currentItem:Object = itemGrid.selectedItem;
var replaced:Object = itemGrid.replaceItemAt(currentItem, currentItem.ID - 1);
itemGrid.selectedItem = itemGrid.getItemAt(currentItem.ID - 1);
itemGrid.replaceItemAt(replaced, currentItem.ID);
updateIDs(itemGrid);
}
}
break;

case itemDownBtn:
if (itemGrid.selectedItem) {
if(itemGrid.selectedItem.ID != itemGrid.rowCount-1) {
currentItem = itemGrid.selectedItem;
replaced = itemGrid.replaceItemAt(currentItem, currentItem.ID + 1);
itemGrid.replaceItemAt(replaced, currentItem.ID);
itemGrid.selectedItem = itemGrid.getItemAt(currentItem.ID + 1);
updateIDs(itemGrid);
}
}
break;

You’ve also got to slap this wee function in too somewhere, it just re-jigs the ID’s to be accurate line references after they’ve moved, so they can move again.

private function updateIDs(targetGrid:DataGrid):void 
{
for (var i:int = 0; i < targetGrid.length; i++) 
{
targetGrid.getItemAt(i).ID = i;
}
}
Tech Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑