Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only the last Cell gets added to the Row

Tags:

c#

asp.net

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!

like image 403
cPeitsch Avatar asked Dec 04 '22 04:12

cPeitsch


1 Answers

is there something I'm missing in C#

Sounds like it, yes.

This:

TableCell iCell = new TableCell();

creates a TableCell object, and assigns a reference to it to the iCell variable. The value of iCell is just a reference to the object. It's not the object itself. This:

iRow.Cells.Add(iCell);

passes that reference to the Add method. It doesn't pass an object to Add - 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:

iCell.Text = "ON";

just overwrite each other, as they're making changes to the same object.

You may find these articles useful:

  • References and values
  • Parameter passing in C#

Personally I would change your code to use collection initializers and object initializers:

TableRow row = new TableRow {
    Cells = {
        new TableCell { Text = "SUBMITTED BY" },
        new TableCell { Text = "ON" },
        new TableCell { Text = "ISSUE DESCRIPTION" },
    }
};
like image 121
Jon Skeet Avatar answered Dec 19 '22 02:12

Jon Skeet