How to Loop Through Items in a List Box and Then Remove Those Item

Delete from ListBox items in a Loop

You cannot add or remove items from a collection while inside a For/Each loop.

Each time you RemoveAt(n), you change the make-up of the collection you are looping. If you remove item #4, item 5 moves up to its slot. Then after Next, your code will be looking at position 5, and be looking at what was originally #6 - item 5 would be skipped entirely. To prevent this every-other one bug/issue, an exception is thrown when using a For/Each.

Secondly, your File.Delete code is trying to reference the item you just removed!

To iterate a collection and remove some/all items one by one, loop backwards using an indexer. This removes from the end of the collection so nothing can "move up". Like this:

' loop backwards using For n
For n as Integer = listHouse.SelectedIndices.Count -1 to 0 Step-1
itemIndex = listHouse.SelectedIndices(n)

MsgBox(listHouse.Items.Item(n).Text & "R.txt")
File.Delete(SourceDir & listHouse.Items.Item(n).Text & "R.txt")

' also remove the thing AFTER you have used it to delete
listHouse.Items.RemoveAt(n)
Next

If you tried to use a forward For n loop with this sort of action, you'd get the every-other one issue.

Using for loop to get selected items in a listbox not working with global variable

You may try with the following.

    for (int i = 0; i < listBox1.Items.Count; i++)
{
MessageBox.Show(listBox1.Items[i].ToString());
}

If for multiple selection, you can retrieve all selected item using code below.

    foreach(int i in listBox1.SelectedIndices)
{
MessageBox.Show(listBox1.Items[i].ToString());
}

Delete from list using foreach using listbox selected item

do this:

class Foo {

BootSaleList bootsalelist;

public void DeleteSale()
{
foreach (BootSale b in lstBootSales.SelectedItems.OfType<BootSale>().ToArray())
{
//temp.Remove(b); -- no more of this guy
bootsalelist.ReturnList().Remove(b);
lstBootSales.Items.Remove(b);

// and no more of these guys:

//lstBootSales.Items.Remove(b.Id);
//lstBootSales.Items.Remove(b.Date);
//DisplayAllBootSales();
}
}

}

where:

[Serializable]
public class BootSaleList : IDisplay
{
private List<BootSale> bootsales;

public List<BootSale> ReturnList()
{
return bootsales;
}
}

and it will work perfectly



Related Topics



Leave a reply



Submit