|
-
February 18th, 2009, 03:35 PM
#1
Listbox Control
Hi All,
I have populated a listbox control with some items and I then want to remove those selected by the user:
Code:
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
If you find my answers helpful, dont forget to rate me 
-
February 18th, 2009, 03:46 PM
#2
Re: Listbox Control
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.
-
February 18th, 2009, 04:43 PM
#3
Re: Listbox Control
a ListBox has a SelectedItems property, use that and then remove each item in that collection.
-
February 19th, 2009, 01:38 AM
#4
Re: Listbox Control
Theres no SeletedItems Property only SelectedItem. I'll have a go with the reverse loop.
If you find my answers helpful, dont forget to rate me 
-
February 19th, 2009, 01:58 AM
#5
-
February 19th, 2009, 01:12 PM
#6
Re: Listbox Control
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:
Code:
int i = 0;
while(i < contactList.Items.Count)
{
if(contactList.Items[i].Selected)
contactList.Items.RemoveAt(i);
else
i++;
}
Alternatively:
Code:
for(int i=contactList.Items.Count-1; i>=0; i--)
{
if(needToBeRemoved...)
contactList.Items.RemoveAt(i);
}
-
February 19th, 2009, 01:49 PM
#7
Re: Listbox Control
BigEd, No there's not. It might be that because I'm using a Web Listbox that it's not there.
Sorry guy's I forgot to say if it was windows or web.
If you find my answers helpful, dont forget to rate me 
-
February 19th, 2009, 02:34 PM
#8
Re: Listbox Control
 Originally Posted by Bill Crawley
BigEd, No there's not. It might be that because I'm using a Web Listbox that it's not there.
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.
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
|