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);
}
}
答案 0 :(得分: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());
}
}
}
答案 1 :(得分: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);