Unable to add duplicate row in asp.net table control

I have an asp.net table management as follows:

TableHeader A Text | Textbox 

What I want to do, in the page_load event, is to duplicate the second line with all the controls inside it, change the text in the first cell and add it as a new line. So here is my code:

  for (int i = 0; i < loop1counter; i++) { TableRow row = new TableRow(); row = myTable.Rows[1]; //Duplicate original row char c = (char)(66 + i); if (c != 'M') { row.Cells[0].Text = c.ToString(); myTable.Rows.Add(row); } } 

But when I execute this code, it just overwrites the original row, and the number of rows in the table does not change. Thanks for the help....

+4
source share
3 answers

As mentioned in the text, you are rewriting the link. Create a new line. Add it to the grid and then copy the cell values โ€‹โ€‹in any way. Sort of:

 TableRow tRow = new TableRow(); myTable.Rows.Add(tRow); foreach (TableCell cell in myTable.Rows[1].Cells) { TableCell tCell = new TableCell(); tCell.Text = cell.Text; tRow.Cells.Add(tCell); } 
+2
source

It is being rewritten because you are rewriting the link. You are not making a copy, essentially row = new TableRow() does nothing.

You should use myTable.ImportRow(myTable.Rows[1]) .

Adjusted based on answer:
row = myTable.Rows[1].MemberwiseClone();

+1
source

try it

 private TableRow CopyTableRow(TableRow row) { TableRow newRow = new TableRow(); foreach (TableCell cell in row.Cells) { TableCell tempCell = new TableCell(); foreach (Control ctrl in cell.Controls) { tempCell.Controls.Add(ctrl); } tempCell.Text = cell.Text; newRow.Cells.Add(tempCell); } return newRow; } 

your code:

 for (int i = 0; i < loop1counter; i++) { TableRow row = CopyTableRow(myTable.Rows[1]); //Duplicate original row char c = (char)(66 + i); if (c != 'M') { row.Cells[0].Text = c.ToString(); myTable.Rows.Add(row); } } 
0
source

All Articles