4

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....

3 Answers 3

2

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);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

but this code just copies the text attribute, in my cells I have Textboxes and FilteredTextBoxExtender(ajaxToolkits) I have to clone them too...
1

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

2 Comments

I couldn't find the ImportRow method. I am using ASP.net Table Control
you can access MemberwiseClone in context of a derived class or within that class itself only.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.