[RESOLVED] multiple items in a listbox
I am trying to remove multiple selected items in a listbox, this code isnt working:
Code:
private void btnRemove_Click(object sender, System.EventArgs e)
{
for (int x = 0; x < lstFiles.Items.Count; x++)
{
if (lstFiles.SelectedIndices.Contains(x))
{
lstFiles.Items.RemoveAt(x);
}
}
}
Not all selected items get removed, but most of them do.
edit: seems its the first thing selected that doesnt get removed.
Re: multiple items in a listbox
Try this:
Code:
private void btnRemove_Click(object sender, System.EventArgs e)
{
for (int x = 0; x != lstFiles.Items.Count; x++)
{
if (lstFiles.SelectedIndices.Contains(x))
{
lstFiles.Items.RemoveAt(x);
}
}
}
Re: multiple items in a listbox
i tried that, and it has the same exact problem, first selected item doesnt get removed.
Re: multiple items in a listbox
If you want to remove multiple items from a collection then you should start from the end and work backwards so that each item you remove does not affect the remaining indices:
Code:
private void btnRemove_Click(object sender, System.EventArgs e)
{
for (int x = lstFiles.Items.Count - 1; x >= 0; lstFiles.Items.Count; x--)
{
if (lstFiles.SelectedIndices.Contains(x))
{
lstFiles.Items.RemoveAt(x);
}
}
}
but in this case you could actually do this:
Code:
while (this.listBox1.SelectedItems.Count > 0)
{
this.listBox1.Items.Remove(this.listBox1.SelectedItems[0]);
}
or this:
Code:
for (int i = this.listBox1.SelectedItems.Count - 1; i >= 0; i--)
{
this.listBox1.Items.Remove(this.listBox1.SelectedItems[i]);
}
Re: multiple items in a listbox
Thanks alot. That fixed it. I understand now why it wasnt removing the right items, I never considered the fact that the indices changed as things got removed.