Simplified Question:
I want to use the following to build an html table dynamically.
//table.Rows[row].Cells.AddRange(new TableCell[] { new TableCell(), new TableCell(), new TableCell(), new TableCell(), new TableCell(), new TableCell() });
for (int row = 0; row < intRows; row++)
{
table.Rows.Add(new TableRow());
table.Rows[row].Cells.AddRange(new TableCell[intCellsPerRow]);
intTableRows = row;
}
I used the commented line before, but it is not flexible, so is not what I want.
The Line: table.Rows[row].Cells.AddRange(new TableCell[intCellsPerRow]); does not work.
How can I get this to work?
Answer Thanks to Heinzi
for (int row = 0; row < dtStructure.Rows.Count / TABLE_COLUMNS; row++)
{
table.Rows.Add(new TableRow());
for (int i = 0; i < CELLS_PER_COLUMN * TABLE_COLUMNS; i++)
{
table.Rows[row].Cells.Add(new TableCell());
}
intTableRows = row;
}
You are adding the same cells to all the rows. This is what happens: After the first iteration, the
(CELLS_PER_COLUMN * TABLE_COLUMNS)cells you created have the first row as their parent. After the second iteration, their parent is changed to the second row, etc.. In the end, they all end up in the last row. Note thatToArraydoes not copy the cells, it just copies the references to the cells into a new array. So all the rows try to share the same cells, which does not work (aWebControlsuch asTableCellcan only have a single parent).For every row, you need to create new cells. I assume that you want something like this:
Untested, since I don’t have Visual Studio available right now, but you should get the idea…
EDIT: I just saw that you edited your question. Your line
does not work, because here you add an empty array of
intCellsPerRowtable cells, i.e., your array contains{null, null, ...}. You need to create each cell withnewlike in my code example above.