Collection was modified; enumeration operation might not execute.

Posted by Chaithragm under C# on 12/27/2013 | Points: 10 | Views : 2057 | Status : [Member] | Replies : 2
foreach (DataRow dr in GridTable.Rows)
{
GridTable.Rows.Add(int.Parse(dr["column1"].ToString()), dr["column2"].ToString(), dr["column3"].ToString(), dr["column4"].ToString(), dr["column5"].ToString(), );
}

Collection was modified; enumeration operation might not execute.




Responses

Posted by: vishalneeraj-24503 on: 12/27/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Hi i got your problem.

What you are doing. You are looping through GridTable rows and inside loop you are again adding rows into that GridTable to whom you are looping through.

Thats why you are getting such error.

Please take another datatable for adding rows.
and take another datatable for looping through rows.

Do not reading and writing rows into same Datatable.


For example:-
foreach (DataRow dr in GridTable.Rows)

{
dt_employee.Rows.Add(int.Parse(dr["column1"].ToString()), dr["column2"].ToString(), dr["column3"].ToString(), dr["column4"].ToString(), dr["column5"].ToString(), );
}


Here both Datatable are different.

Chaithragm, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Allemahesh on: 12/27/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Modify you code as per below one:-

public void loopDataTable()
{
DataTable GridTable = CreatedDataTable();
DataRow drRow = GridTable.NewRow();
drRow[0] = 1;
drRow[1] = "column2";
drRow[2] = "column3";
drRow[3] = "column4";
drRow[4] = "column5";
GridTable.Rows.Add(drRow);

DataTable GridTable1 = CreatedDataTable();
foreach (DataRow dr in GridTable.Rows)
{
GridTable1.Rows.Add(int.Parse(dr["column1"].ToString()), dr["column2"].ToString(), dr["column3"].ToString(), dr["column4"].ToString(), dr["column5"].ToString());
}
}

public DataTable CreatedDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("column1", typeof(int)));
dt.Columns.Add(new DataColumn("column2", typeof(string)));
dt.Columns.Add(new DataColumn("column3", typeof(string)));
dt.Columns.Add(new DataColumn("column4", typeof(string)));
dt.Columns.Add(new DataColumn("column5", typeof(string)));
return dt;
}


Chaithragm, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response