views:

33

answers:

2

I am attempting to remove rows on my asp.net page using the following code:

    try
    {
        Table t = (Table)Page.FindControl("Panel1").FindControl("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?

A: 

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);
}
Snake
That's a very strange loop. `x` is always 0, which means you are always removing the first element, which is probably very slow (O(N^2), I suspect).
Marcelo Cantos
+4  A: 

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--)
Jamiec
I find this cleaner: for(int i=t.Rows.Count;i-->0;)
Marcelo Cantos