Array copy fails in loop
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 that ToArray
does 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 (a WebControl
such as TableCell
can only have a single parent).
For every row, you need to create new cells. I assume that you want something like this:
for (int row = 0; row < datatable.Rows.Count / 6; row++)
{
table.Rows.Add(new TableRow());
for (int i = 0; i < CELLS_PER_COLUMN * TABLE_COLUMNS; i++)
{
table.Rows[row].Cells.Add(new TableCell());
}
}
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
table.Rows[row].Cells.AddRange(new TableCell[intCellsPerRow]);
does not work, because here you add an empty array of intCellsPerRow
table cells, i.e., your array contains {null, null, ...}
. You need to create each cell with new
like in my code example above.
Your for
loop is using a variable named datatable
as a constraint. But inside your block,
you're adding the rows to a variable named table
. Are these the same?
for (int row = 0; row < datatable.Rows.Count / 6; row++)
{
TableCell[] arrCells = lCells.ToArray<TableCell>();
table.Rows.Add(new TableRow());
// Snip for brevity
}
Curious: What's with the / 6
? If you're just trying to get the rows into the table in order, why would you need to do this for every 6th row?
This is not the most efficient, but the lazy in me would write it this way:
table.Rows[row].Cells.AddRange(
new TableCell[intCellsPerRow].Select(c=>new TableCell()).ToArray());
精彩评论