Click here to Skip to main content
13,737,531 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked
Posted 20 Mar 2011
Licenced CPOL

How to Delete Selected Items of ListView and ListBox (Snippets)

, 20 Mar 2011
Rate this:
Please Sign up or sign in to vote.
I have some lessons learned on the topic.

With ListView and ListBox, you can have multiple selections when you set the property to do so. There are different ways to delete all selected items from a ListView and a ListBox, right or wrong. I have some lessons learned on the topic.
1. Use For Each loop in ListView. (It works)

For Each i As ListViewItem In ListView1.SelectedItems

2. Use For Each loop in ListBox. (It doesn’t work)

'For Each i As Object In ListBox1.SelectedItems
'    ListBox1.Items.Remove(i)
  • The For-Each loop does not work correctly with ListBox as it does with ListView. It causes a System.InvalidOperationException: List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

3. A fix to the problem is to copy the selected items to a list.

Dim lst As New List(Of Object)
For Each a As Object In ListBox1.SelectedItems
For Each a As Object In lst

4. Use Index, the right way and the wrong way.

The following snippet works but it must use an inverse loop.

For i As Integer = ListBox1.SelectedIndices.Count - 1 To 0 Step -1

The other way (using a normal loop) will not work.

'For i As Integer = 0 To ListBox1.SelectedIndices.Count - 1
'    ListBox1.Items.RemoveAt(ListBox1.SelectedIndices.Item(i))

But amazingly, the following modification works.

For i As Integer = 0 To ListBox1.SelectedIndices.Count - 1

5. Use Do While loop. (This would be the best one based on its clear logic)

Do While (ListBox1.SelectedItems.Count > 0)

In fact, the ListBox1.SelectedItem (or SelectedIndex) is always the first one of the ListBox1.SelectedItems (or SelectedIndices).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

Riccardo Loi16-Aug-15 10:51
memberRiccardo Loi16-Aug-15 10:51 
QuestionWOW Pin
Member 1044903826-Oct-14 0:46
memberMember 1044903826-Oct-14 0:46 
GeneralHey, nifty. Thanks. Pin
Br.Bill21-Mar-11 16:20
memberBr.Bill21-Mar-11 16:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180920.1 | Last Updated 20 Mar 2011
Article Copyright 2011 by PdotWang
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid