I am attempting to remove rows on my asp.net page using the following code:
try
{
Table t = (Table)Page.FindControl("Panel1").FindControl开发者_如何学C("tbl");
foreach (TableRow tr in t.Rows)
{
t.Rows.Remove(tr);
}
}
catch (Exception e)
{
lblErrorMessage.Text = "Error - RemoveDynControls - " + e.Message;
}
however, I am getting an error on the (when the code loops the second time around) "Collection was modified; enumeration operation may not execute."
Any ideas regarding what is causing the error message?
If you want to clear all rows you can
t.Rows.Clear();
If you need to remove certain rows, go backwards through the collection
for(int i=t.Rows.Count-1;i>0;i--)
Since foreach uses an enumerator in the generated code you cannot use foreach.
When you delete a row you invalidate the underlying Collection which triggers that exception.
You should use a for loop. That'll do the trick
for(int x = 0;x < t.Rows.Count; x++)
{
t.Rows.RemoveAt(x);
}
精彩评论