|
-
Nov 6th, 2005, 10:43 AM
#1
Thread Starter
Junior Member
[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.
Last edited by Triumph; Nov 6th, 2005 at 11:44 AM.
-
Nov 6th, 2005, 11:42 AM
#2
Lively Member
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);
}
}
}
-
Nov 6th, 2005, 11:45 AM
#3
Thread Starter
Junior Member
Re: multiple items in a listbox
i tried that, and it has the same exact problem, first selected item doesnt get removed.
-
Nov 6th, 2005, 04:55 PM
#4
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]);
}
Last edited by jmcilhinney; Nov 6th, 2005 at 06:31 PM.
-
Nov 6th, 2005, 06:17 PM
#5
Thread Starter
Junior Member
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|