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
Conversion of System.Array to List
Cancellation Token in Task Constructor: Why
How to Print the Current Stack Trace in .Net Without Any Exception
Handle Modelstate Validation in ASP.NET Web API
How to Read an Entire File to a String Using C#
Replace Multiple Characters in a C# String
Close a Messagebox After Several Seconds
Get All Inherited Classes of an Abstract Class
Difference Between "\N" and Environment.Newline
Is There a Downside to Adding an Anonymous Empty Delegate on Event Declaration
ASP.NET MVC 2 - Bind a Model's Property to a Different Named Value
Automatically Set Appsettings.JSON for Dev and Release Environments in ASP.NET Core
Turn a Simple C# Dll into a Com Interop Component
An Object Reference Is Required to Access Non-Static Member