user3723271
user3723271

Reputation:

Clearing Multi-Selected Items From Listbox C#

What i've tried:

try 1:

for(int x = listBox1.SelectedIndices.Count - 1; x>= 0; x--)
{ 
    int idx = listBox1.SelectedIndices[x];
    listBox2.Items.Add(listBox1.Items[idx]); 
    listBox1.Items.RemoveAt(idx);
} 

try 2:

ArrayList tmpArr = new ArrayList();
foreach (object obj in listBox1.SelectedItems)
{
    listBox2.Items.Add(obj);
    tmpArr.Add(obj);
}
foreach (object obj in tmpArr.ToArray())
{
    listBox1.Items.Remove(obj);
}

Also tried everything in the following post: How to remove multiple selected items in ListBox?

Still nothing worked. What am I doing wrong?

Upvotes: 0

Views: 1284

Answers (2)

user4618993
user4618993

Reputation:

listbox1.BeginUpdate();

for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--)
{
    int idx = listBox1.SelectedIndices[x];
    listBox1.Items.RemoveAt(idx);
}

listbox1.EndUpdate();

If you cannot guarantee that every object in the list is unique, then this is the correct way to do it, to ensure that the correct selected items get removed.

If you have multiples of the same object in your listbox, you have to refer to them by "index", otherwise if you remove them by "item" it will remove the first instance of any matching items it finds.

I am in the process of writing a bus route planner which called for replication of the waypoint markers in the list. These were stored as strings, so for example I might have had "w1", "w2", "w3"... "w2" (think of a bus going down a high street, looping round a couple of blocks and then returning down the other side to understand why I have that... I only need waypoint markers in the centre of the road, not in each lane)

If I had selected the last "w2" marker as part of a range and used the selectedItem() method to to remove them, it would have removed the first "w2", not the second one. By using the SelectedIndex() method, it removes based on position, not value, so duplicate values are left safely intact.

I just wanted to add that as I have just been dealing with this very same problem, so saw first hand the problem removing by SelectedItem() caused.

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54417

var selectedItems = new object[listBox1.SelectedItems.Count];

listBox1.SelectedItems.CopyTo(selectedItems, 0);

foreach (var item in selectedItems)
{
    listBox1.Items.Remove(item);
}

or with a bit of LINQ to simplify the code:

foreach (var item in listBox1.SelectedItems.Cast<object>().ToArray())
{
    listBox1.Items.Remove(item);
}

The reasoning here is that you get all the selected items and put them into another list first. The original issue is that any change you make to the ListBox will change things like SelectedItems and SelectedIndices. Once you've created an independent array and put the selected items into it, nothing you do to the ListBox will affect that array so you can just enumerate it normally.

Upvotes: 2

Related Questions