开发者

Can't add duplicate row to the asp.net Table Control

I have an asp.net table control like this:

  TableHeader
A Text | Textbox

What I want to do is, in the page_load event, duplicate second row with all the controls within it, change开发者_运维百科 the text in the first cell and add as a new row. 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 justs overwrites on the original row and row count of the table doesn't change. Thanks for help....


As thekip mentioned, you are re-writing the reference. Create a new row. Add it to the grid and then copy the cell values in whatever manner you want. Something like:

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);
 }


It gets overwritten because you overwrite the reference. You don't do a copy, essentially the row = new TableRow() is doing nothing.

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

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


so try this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜