I’m trying to manually add three headers to a table. The table fills out fine with data from the SqlDataReader, but I’m having trouble getting the first row to stick.
TableRow iRow = new TableRow();
TableCell iCell = new TableCell();
iCell.Text = "SUBMITTED BY";
iRow.Cells.Add(iCell);
iCell.Text = "ON";
iRow.Cells.Add(iCell);
iCell.Text = "ISSUE DESCRIPTION";
iRow.Cells.Add(iCell);
table.Rows.Add(iRow);
causes only the last entry, in this case, ISSUE DESCRIPTION, to show up on the table. I’ve found a workaround in
TableRow iRow = new TableRow();
TableCell iCell = new TableCell();
TableCell iCell2 = new TableCell();
TableCell iCell3 = new TableCell();
iCell.Text = "SUBMITTED BY";
iRow.Cells.Add(iCell);
iCell2.Text = "ON";
iRow.Cells.Add(iCell2);
iCell3.Text = "ISSUE DESCRIPTION";
iRow.Cells.Add(iCell3);
table.Rows.Add(iRow);
but it’s bothering me how much messier that is. Is something wrong with my logic, or is there something I’m missing in C#? I’ve got a pretty good handle on C, but just started C# a couple weeks ago.
Thanks!
Sounds like it, yes.
This:
creates a
TableCellobject, and assigns a reference to it to theiCellvariable. The value ofiCellis just a reference to the object. It’s not the object itself. This:passes that reference to the
Addmethod. It doesn’t pass an object toAdd– you can never do that in C#. So your row ends up with lots of references to the same cell, and all the changes you’ve made in lines like this:just overwrite each other, as they’re making changes to the same object.
You may find these articles useful:
Personally I would change your code to use collection initializers and object initializers: