954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

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

0
By PdotWang on Mar 20th, 2011 7:24 pm

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 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
    ListView1.Items.Remove(i)
Next


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

'For Each i As Object In ListBox1.SelectedItems
'    ListBox1.Items.Remove(i)
'Next


*The foreach loop does not work with ListBox as the way it is does with ListView. It causes 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
        lst.Add(a)
    Next
    For Each a As Object In lst
        ListBox1.Items.Remove(a)
    Next


(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
    ListBox1.Items.RemoveAt(ListBox1.SelectedIndices.Item(i))
Next




The other way doesn’t work.

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


But amazingly, this modification works.

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




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

Do While (ListBox1.SelectedItems.Count > 0)
    ListBox1.Items.Remove(ListBox1.SelectedItem)
Loop


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

I am new here. I do not know how to put it in the Code Snippets area. Sorry for showing it twice.

PdotWang
Newbie Poster
20 posts since Mar 2011
Reputation Points: 27
Solved Threads: 5
 

>I am new here. I do not know how to put it in the Code Snippets area. Sorry for showing it twice.

@PdotWang

Sorry! I'm not getting you. Do you have any problem or you want to make this thread as "Code Snippet"?

__avd
Posting Genius (adatapost)
Moderator
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

I moved it to the Code Snippet Section.

WolfPack
Postaholic
Moderator
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You