Click to See Complete Forum and Search --> : Listbox Control
Bill Crawley
February 18th, 2009, 02:35 PM
Hi All,
I have populated a listbox control with some items and I then want to remove those selected by the user:
foreach (ListItem li in ContactList.Items)
{
if (li.Selected == true)
{
ContactList.Items.Remove(li.Text);
}
}
trouble is as soon as the first item is removed code crashes because the foreach is now out of sync.
HOw can I force only those items selected to be removed
Peter_B
February 18th, 2009, 02:46 PM
The usual way to do this is to loop through the items in reverse - that way the removals do not affect the part of the collection which you still have to go through.
BigEd781
February 18th, 2009, 03:43 PM
a ListBox has a SelectedItems property, use that and then remove each item in that collection.
Bill Crawley
February 19th, 2009, 12:38 AM
Theres no SeletedItems Property only SelectedItem. I'll have a go with the reverse loop.
BigEd781
February 19th, 2009, 12:58 AM
Yes there is (http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(VS.80).aspx)
Talikag
February 19th, 2009, 12:12 PM
It's not such a smart idea to change the size of list of items, during running on it in a for/foreach loop.
You could use the while loop instead:
int i = 0;
while(i < contactList.Items.Count)
{
if(contactList.Items[i].Selected)
contactList.Items.RemoveAt(i);
else
i++;
}
Alternatively:
for(int i=contactList.Items.Count-1; i>=0; i--)
{
if(needToBeRemoved...)
contactList.Items.RemoveAt(i);
}
Bill Crawley
February 19th, 2009, 12:49 PM
BigEd, No there's not. It might be that because I'm using a Web Listbox that it's not there.
<asp:ListBox .....
Sorry guy's I forgot to say if it was windows or web.
BigEd781
February 19th, 2009, 01:34 PM
BigEd, No there's not. It might be that because I'm using a Web Listbox that it's not there.
<asp:ListBox .....
Sorry guy's I forgot to say if it was windows or web.
Yes, that would be why. A standard WinForms ListBox has that property.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.