2017-07-21 90 views
0

System.InvalidOperationException:集合已被修改;可能無法執行枚舉操作

private void btnGetUpdatedSchema_Click(object sender, EventArgs e) 
{ 
    lviewMainDbSchema.Items.Clear(); 

    string conString = null; 

    conString = "Data source=" + txtUpdatedServerName.Text + ";Password=" + txtUpdatedPassword.Text + ";Initial Catalog=" + txtUpdatedDatabaseName.Text + ";User ID=" + txtUpdatedUserId.Text + ";"; 
    con = new SqlConnection(conString); 
    try 
    { 
     int tblTotal = 0; 
     GetTables(conString, tblMainList, tblTotal); 
     foreach (var list in tblMainList) 
     { 
      con.Open(); 
      string query = "SELECT * FROM" + " " + list; 
      cmd = new SqlCommand(query, con); 
      dr = cmd.ExecuteReader(); 
      dt = dr.GetSchemaTable(); 
      con.Close(); 

      foreach (DataRow dt_row in dt.Rows) 
      { 
       foreach (DataColumn dt_col in dt.Columns) 
       { 
        lviewMainDbSchema.Items.Add(string.Format("{0}={1}", dt_col.ColumnName, dt_row[dt_col]).ToString()); 

        //HERE WHERE I GOT THE ERROR!! :) :) :) <3 
        tblMainList.Add(string.Format("{0}={1}", dt_col.ColumnName, dt_row[dt_col]).ToString()); 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show("ERROR!!!!" + ex); 
    } 
} 
  1. 列表項

回答

1

您不能修改您通過foreach循環枚舉列表的對象。使用for循環intead。

for(int i = 0; i < tblMainList.Count(); i++) 
{ 
     foreach (DataRow dt_row in dt.Rows) 
     { 
      foreach (DataColumn dt_col in dt.Columns) 
      { 
       lviewMainDbSchema.Items.Add(string.Format("{0}={1}", dt_col.ColumnName, dt_row[dt_col]).ToString()); 

       //HERE WHERE I GOT THE ERROR!! :) :) :) <3 
       tblMainList.Add(string.Format("{0}={1}", dt_col.ColumnName, dt_row[dt_col]).ToString()); 
       } 
      } 
     } 
0

你可以使用一個單獨的List<string>新項目添加到再後來這增加了迭代List

List<string> addItems = new List<string>(); 
foreach(var list in tblMainList) 
{ 
    con.Open(); 
    string query = "SELECT * FROM"+" "+list; 
    cmd = new SqlCommand(query, con); 
    dr = cmd.ExecuteReader(); 
    dt = dr.GetSchemaTable(); 
    con.Close(); 

    foreach (DataRow dt_row in dt.Rows) 
    { 
     foreach (DataColumn dt_col in dt.Columns) 
     { 
       lviewMainDbSchema.Items.Add(string.Format("{0}={1}", dt_col.ColumnName, dt_row[dt_col]).ToString()); 

       //add new items to new list 
       addItems .Add(string.Format("{0}={1}", dt_col.ColumnName, dt_row[dt_col]).ToString()); 
     } 
    } 
} 

// add new List to tblMainList 
tblMainList.AddRange(addItems); 
+0

謝謝工程:) –

相關問題