bgx:components logo
© 2004 -2005
Bernhard Gaul



Deleting Multiple Selections from a List Component Instance

The following came up in a newsgroup and may be interesting for others. The question was how to delete multiple selections from a List and select the next item after the last deleted one or the first one if there aren't further items.

The problem with deleting multiple selections is that you can only remove one item at a time, but after removing an item the indices within the List shift and do not correspond to the originally selected indices.

The trick I use is to copy the selectedIndices, sort them (because they are in order of selection, not in order of position in the List) and loop through this copy, offsetting every next index with the number of items already deleted.

If you don't want to select anything after the deletion just leave out the last bit of the following code.

[BTW: The Bgx Lexible List has a removeSelected() method which removes all currently selected items without further coding.]

The Code

for (var i = 0 ; i < 20; i++)
{
	mcList.addItem("item " + i);
}

btnDelete.onRelease = function()
{
	//do nothing when no selection exists
	if (typeof mcList.selectedIndex == "undefined") return;
	//copy existing indices
	var currentIndices = mcList.selectedIndices;
	//sort them so you can access them in order
	currentIndices.sort();
	for (var i = 0; i < currentIndices.length; i++)
	{
		//as the inidices of the list shift as you go on deleting
		//you have to offset the last index by the number
		//of indices already deleted
		var thisIndex = currentIndices[i] - i;
		mcList.removeItemAt(thisIndex);
	}
	//select item after the last deletion which has the same index 
	//as the last deleted one, because it shifted up
	if (mcList.length > thisIndex)
	{
		mcList.selectedIndex = thisIndex;
	}
	else
	{
		mcList.selectedIndex = 0;
	}
}

The Example