问题
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
回答1:
while(LB_upload.Items.Count > 0)
{
ftp.Upload(LB_upload.Items[0].ToString());
LB_upload.Items.RemoveAt(0);
}
回答2:
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.
回答3:
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);
}
}
来源:https://stackoverflow.com/questions/1400091/search-and-remove-item-from-listbox