views:

174

answers:

3

Is there a way to remove an item from a listbox based on a string?

I have been playing around for a few minutes and here is what i have so far but its not working

foreach(string file in LB_upload.Items)
{
    ftp.Upload(file);
    int x = LB_upload.Items.IndexOf(file);
    LB_upload.Items.RemoveAt(x);
}

I could just loop through each item but I wanted to do something a little more elegant

+2  A: 

Based on your example, I'd do something like;


foreach(string file in LB_upload.Items)
{
  ftp.Upload(file);
}
LB_upload.Items.Clear();

The problem you are probably encountering is that you are altering the list while iterating over this. This is a big no-no, and has been covered ad-nauseum on this site.

John Kraft
LOL, good solution!
Sorin Comanescu
ha yea i guess this is the most elegant way (1 line of code).
Crash893
+2  A: 
while(LB_upload.Items.Count > 0)
{
  ftp.Upload(LB_upload.Items[0].ToString());
  LB_upload.Items.RemoveAt(0);
}
Petoj
I liked this one too but i think John kraft is the winner
Crash893
I changed to this as the answer. I had to add a this.refresh to show the updates of the box. The reason was because I wanted to 1) show that files were moving and 2 if there was a problem you would see what files are left.
Crash893
+2  A: 

Based on the title of your question it sounds like you don't want to remove every item, just some of them. If that's the case:

for (int i = LB_upload.Items.Count - 1; i >= 0; i--)
{
    if (somecondition)
    {
        ftp.Upload(LB_upload.Items[i]);
        LB_upload.Items.RemoveAt(i);
    }
}
Jon B
+1 thanks for the idea
Crash893