Kaly
Kaly

Reputation: 99

Moving all selected items in listbox multiple selection

i can't get to move all selected items in listbox to the second listbox, here is the code:

void moveIn(ListBox inMoveOut, ListBox inMoveIn) {
inMoveOut.setMultipleSelect(true);
inMoveIn.setMultipleSelect(true);
    // for each item in the listbox
    for (int i = 0; i < inMoveOut.getItemCount(); i++) {
        if (inMoveOut.isItemSelected(i)) {
            // add item from the first listbox to the second lsitbox
            inMoveIn.addItem(inMoveOut.getItemText(i), inMoveOut.getValue(i));
            // delete item from the first listbox
            inMoveOut.removeItem(i);
        }
    }

}

i can select multiple items but can only move throw one item, not all selected items. Any suggestions please.

Upvotes: 0

Views: 372

Answers (2)

Baz
Baz

Reputation: 36884

Since you are removing items in the loop, you're changing the loop limits. If you start at the end and move to the beginning, this won't matter:

int size = inMoveOut.getItemCount()
for (int i = size - 1; i >= 0 ; i--) {
    if (inMoveOut.isItemSelected(i)) {
        // add item from the first listbox to the second lsitbox
        inMoveIn.addItem(inMoveOut.getItemText(i), inMoveOut.getValue(i));
        // delete item from the first listbox
        inMoveOut.removeItem(i);
    }
}

This will however add them in reverse order. So here's an alternative:

// First, copy them across
for (int i = 0; i < inMoveOut.getItemCount(); i++) {
    if (inMoveOut.isItemSelected(i)) {
        // add item from the first listbox to the second lsitbox
        inMoveIn.addItem(inMoveOut.getItemText(i), inMoveOut.getValue(i));
    }
}

// Then delete them
for (int i = 0; i < inMoveOut.getItemCount(); i++) {
    if (inMoveOut.isItemSelected(i)) {
        // delete item from the first listbox
        inMoveOut.removeItem(i);
    }
}

This is a bit less efficient, but it'll do the job.

Upvotes: 1

Srinivas Cheruku
Srinivas Cheruku

Reputation: 1364

Suppose for the first iteration, the item is moved from 'inMoveOut' to 'inMoveIn', but, the moment the line - inMoveOut.removeItem(i) executes, the size of ListBox is changed, ( i.e,inMoveOut.getItemCount() is now having a different value ), and your 'for loop' will still iterate inMoveOut.getItemCount() times, which actually is having the old item count.

I think this could be the reason.

You can look out for using 'foreach' kind of a thing, so that you get rid of indexing and fetching the items.

for(ListBox item: inMoveOut)
{
// logic here
}

Upvotes: 0

Related Questions