Iteration over TableRowCollection -> list [...] modified exception

B

Ben Schwehn

Hello everyone!

I have a control that derives from WebControls.Table. This control has a
method CreateTable() that builds a simple table. I also have second
control that, again, derives from Table. This control instantiates an
instance of the first control and then i want to copy all the rows of this
control into this.Rows like this:

TableControl1 tc1 = new TableControl1(); tc1.CreateTable(); foreach
(TableRow tr in tc1.Rows)
this.Rows.Add(tr);

And what i get is a exception:

The list that this enumerator is bound to has been modified. An enumerator
can only be used if the list doesn't change.


i don't quite understand what happens here. Apparently Rows.Add somehow
changes the original RowCollection...

Could anyone tell me what happens and why?

Also, what is the recommended way to copy all rows from one table into
another table. Ideally i don't want a copy of the original rows to be
made, I just want to put the references to the orignial rows into the
second table's Row collection.

I added a complete sample that shows this behaviour below.
Thanks a lot :eek:)

Ben



using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace tester
{

[ToolboxData("<{0}:TableControl1 runat=server></{0}:TableControl1>")]

public class TableControl1 : System.Web.UI.WebControls.Table {
protected override void CreateChildControls() {
CreateTable();
}
public void CreateTable() {
TableRow tr = new TableRow();
TableCell td = new TableCell();
td.Text = "test";
tr.Cells.Add(td);
this.Rows.Add(tr);
TableRow tr2 = new TableRow();
TableCell td2 = new TableCell();
td2.Text = "test2";
tr2.Cells.Add(td2);
this.Rows.Add(tr2);
TableRow tr3 = new TableRow();
TableCell td3 = new TableCell();
td3.Text = "test3";
tr3.Cells.Add(td3);
this.Rows.Add(tr3);
}
}
public class TableControl2 : System.Web.UI.WebControls.Table {
protected override void CreateChildControls() {
TableControl1 tc1 = new TableControl1();
tc1.CreateTable();
foreach(TableRow tr in tc1.Rows)
this.Rows.Add(tr);
}
}
}
 
B

Ben Schwehn

Also, what is the recommended way to copy all rows from one table into
another table. Ideally i don't want a copy of the original rows to be
made, I just want to put the references to the orignial rows into the
second table's Row collection.

propbably not a good idea because control has a field owner and other
things that have to be changed
I use an array and Copyto now and it seems to work

ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top