2016-06-18 7 views
-1

Also habe ich dieses Fehler in dem Wort in "in" im foreach Zyklus und ich surfte das Netz, aber ich habe keine Antworten gefunden oder verstanden, hier ist der Code.Liste, an die dieser Enumerator gebunden ist, wurde geändert. Ein Enumerator kann nur verwendet werden, wenn sich die Liste nicht ändert

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(); 

     } 
+2

Sie sind das Hinzufügen von Text zu 'lstitems.Items', während Sie es iterieren. Tu das nicht. Entfernen Sie die Zeile 'lstitems.Items.Add (txtcodproduto.Text +", "+ txtnomeprod.Text +", "+ txtquantidade.Text +", "+ txtpreco.Text +", "+ txttamanho.Text +", "+ total); ' – Rob

+0

Ist das eine Endlosschleife? Sie fügen in jeder Iteration ein Element hinzu, und wie endet die Schleife? – user3185569

+0

Ja, ich habe es, reiner Mangel an Aufmerksamkeit, Entschuldigung und danke! –

Antwort

0

können Sie keine List ändern, während Sie ein foreach verwenden darüber iterieren.

Stattdessen können Sie eine normale for Schleife verwenden.

Beispiel:

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

    Console.WriteLine(item); 
} 

Aber man kann:

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

    Console.WriteLine(mylist[i]); 
} 
+0

Warum der Downvote? – user3185569

Verwandte Themen