Search and remove item from listbox

萝らか妹 提交于 2019-12-23 03:59:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!