1

So i got this errorin the word in "in" in the foreach cycle and i surfed the net but i didnt found any answers or understood it, here is the code.

foreach (string items in lstitems.Items)
        {
            connection.Open();
            OleDbCommand comando = new OleDbCommand();
            comando.Connection = connection;

            string[] caracteresnastring = items.Split(new char[] { ',' }).ToArray();
            string codproduto = caracteresnastring[0];
            string nome = caracteresnastring[1];
            int quantidade = Convert.ToInt32(caracteresnastring[2]);
            decimal preco = Convert.ToDecimal(caracteresnastring[3]);

            int tamanho = Convert.ToInt32(caracteresnastring[4]);
            string total = caracteresnastring[5];
            lstitems.Items.Add(txtcodproduto.Text + "," + txtnomeprod.Text + "," + txtquantidade.Text + "," + txtpreco.Text + "," + txttamanho.Text + "," + total);



            comando.CommandText = "INSERT INTO detalhes_encomendas_fornecedores (cod_encomenda_forn, cod_produto,quantidade,tamanho, total) VALUES('" + codencomendaforn + "','" + codproduto + "', '" + quantidade + "', '" + tamanho + "', '" + total + "'); ";
            comando.ExecuteNonQuery();
            connection.Close();

        }
Ricardo Pires
  • 39
  • 1
  • 7
  • 2
    You are adding text to `lstitems.Items` while you are iterating it. Don't do that. Remove the line `lstitems.Items.Add(txtcodproduto.Text + "," + txtnomeprod.Text + "," + txtquantidade.Text + "," + txtpreco.Text + "," + txttamanho.Text + "," + total);` – Rob Jun 18 '16 at 16:02
  • Is this an infinite loop ? you add one item in each iteration, then how does the loop end ? – Zein Makki Jun 18 '16 at 16:02
  • Yeah i got it , pure lack of attention , sorry and thank you ! – Ricardo Pires Jun 18 '16 at 16:18

1 Answers1

3

You can't modify a List while you're using a foreach to iterate over it.

Instead, you can use a normal for loop.

Example:

foreach(int item in mylist)
{
    if (item % 2 == 0)
        mylist.Remove(item); // Error here

    Console.WriteLine(item);
}

But you can:

for(int i = 0; i < mylist.Count; i++)
{
    if (mylist[i] % 2 == 0)
    {
        mylist.RemoveAt(i);
        i--;
        continue;
    }

    Console.WriteLine(mylist[i]);
}
Zein Makki
  • 29,485
  • 6
  • 52
  • 63