Red Gordon
Red Gordon

Reputation: 43

.net web tables with same row

I am programmatically creating tables for a web page in ASP.Net. Basically I am running a SQL query and selecting data to be used as part of different tables on this page. Sometimes the same data is used in multiple tables.

TableRow row = new TableRow();
/* ...
    assign cells to row
*/
table1.Rows.Add(row);
table2.Rows.Add(row);

The row in table 1 becomes corrupted in some way. It won't display during debuging. Not an empty cell, just nothing.

I put a watch on the the first cell of the new row of table1 to check the value after creation; and immediately following being added to table1 it looks good. As soon as I step over adding row to table2 the watch pane says

[The value of this expression may be incorrect. It could not be evaluated because: "new System.Linq.SystemCore_enumerableDebugView(((System.Web.UI.WebControls.TableRow)new System.Linq.SystemCore_EnumerableDebugView(table1.Rows).Items[4].Cells).Items[0]' threw an exception of type 'System.IndexOutOfRangeException]

I believe this has something to do with objects being sent by reference rather than by value, but I don't see why this is causing a problem. The TableRow class doesn't have a copy or clone routine to use. I've also tried putting my data in TableCell[] and moving that into TableRow at the last minute, but this hasn't made a difference.

Upvotes: 0

Views: 235

Answers (1)

Jesse Squire
Jesse Squire

Reputation: 7755

TableRow derrives from System.Web.Control indirectly, via WebControl. A control keeps a direct reference to it's parent, of which it can only have one. When you add the row to table2 you are implicitly removing it from table1.

If you look at the source for the TableRowCollection type, which is what Table.Rows is, you'll see that the AddAt method contains the line: this.owner.Controls.AddAt(index, row); That, effectively, makes the TableRow a child control of the last Table to which it was added.

The cells of the table work much the same way. To avoid this, you'll have to create a new TableRow instance with new cells to hold your data. I didn't find a native method to do a deep copy of a TableRow, so you're likely to need to write one on your own.

Upvotes: 1

Related Questions