简体   繁体   中英

C# foreach and listbox remove item

i have an issue with operator Foreach that i use to to take matches and put them in other listbox. the problem is i need to take al matches from an file, and put them in listbox2 or 3. but from listbox1 need to remove only item(0).

now, if in the file matches are 5,6,7 etc. it's going to put them all ass i need in listbox2 or 3, but also it's going to remove 5,6,7 etc. items from listbox1. i need to remove only once item(0) from listbox1. here is code. thanks!

foreach (Match match in matches)
{
    if (matches.Count > 0)
    // if (match.Success)
    {
        label6.Text = "found!";
        listBox2.Items.Add(searchemailKOK + "|" + match);
        progressBar1.Increment(1);
        pictureBox3.Height = (200 - (progressBar1.Value / 2));
        label1.Text = listBox1.Items.Count.ToString();
        label2.Text = listBox2.Items.Count.ToString();
        timer2.Start();
        if (listBox1.Items.Count > 0)
        {
            listBox1.Items.RemoveAt(0); 
        }
        timer1.Stop();
     }
 } 

you can not delete item from list using foreach loop as it will change the structure of the list it is currently operating on. hence exception will be thrown.

you can use for loop but you need to use it in reverse

for(int = list.count-1; i >= 0; i--)
{
    if(list[i].id == 5)
       list.RemoveAt(i)
}

Solved moving

if (listBox1.Items.Count > 0)
    {
        listBox1.Items.RemoveAt(0); 
    }

to timer2.

thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM