Remove items from listbox

B

Bill Nguyen

I use the following example (from another post) and it seemed to work fine.
However, when I add the syntax to remove the selected item from the
senderbox, I got error.
senderBox.Items.RemoveAt(senderbox.selectedIndex)

I was told that I need to copy selecteditems to an array and run the For
each routine from the array instead. Can someone please give me some idea
on how to accomplish this?
Thanks a million.

Bill


Private Sub lb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles lb1.SelectedIndexChanged

Dim o As Object

Dim senderBox As ListBox

senderBox = DirectCast(sender, ListBox)

lb2.Items.Clear()

For Each o In senderBox.SelectedItems

lb2.Items.Add(o)

' to remove from senderBox

senderBox.Items.RemoveAt(senderbox.selectedIndex)


Next

End Sub
 
P

Peter van der Goes

Bill Nguyen said:
I use the following example (from another post) and it seemed to work fine.
However, when I add the syntax to remove the selected item from the
senderbox, I got error.
senderBox.Items.RemoveAt(senderbox.selectedIndex)

I was told that I need to copy selecteditems to an array and run the For
each routine from the array instead. Can someone please give me some idea
on how to accomplish this?
Thanks a million.

Bill


Private Sub lb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal
e
As System.EventArgs) Handles lb1.SelectedIndexChanged

Dim o As Object

Dim senderBox As ListBox

senderBox = DirectCast(sender, ListBox)

lb2.Items.Clear()

For Each o In senderBox.SelectedItems

lb2.Items.Add(o)

' to remove from senderBox

senderBox.Items.RemoveAt(senderbox.selectedIndex)


Next

End Sub
Have you used the debugger to step through your code in the event procedure?
Take note of the value of selectedIndex the second time through your loop.
As the item related to the selected index has been removed, my test
indicates the value of SelectedIndex is now -1, which throws the
System.ArgumentOutOfRangeException.
I'd recommend you look at the ArrayList class instead of using an array.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top