0

Adding a table dynamically in code behind I can do something like...

TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = "blah blah blah";
row.Cells.Add(cell1);
myTable.Rows.Add(row);

but what if the order of the table rows depends on the user input....so for each iteration it is either going to be A or B. If it is A, extend row a...If it is B, extend row b

after 1st iteration
A: 123

after 2nd iteration
A: 123
B: abc

after 3rd iteration
A: 123456
B abc

after 4th iteration
A: 123456789
B: abc

Ive tried rows.addAt(index, row); but its not working says index is out of range. is this even the correct way to do this? thanks for any replies

    //forloop
   {
    if(A)
    {
    TableRow row = new TableRow();
    TableCell cell1 = new TableCell();
    cell1.Text = "blah blah blah";
    row.Cells.Add(cell1);
    myTable.Rows.AddAt(0, row);
    }

    if(B)
    {
    TableRow row = new TableRow();
    TableCell cell1 = new TableCell();
    cell1.Text = "blah blah blah";
    row.Cells.Add(cell1);
    myTable.Rows.Add(1, row);
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
John
  • 103
  • 1
  • 3
  • 11
  • So, if I understand you correctly, you want to change the value of row A or row B, or you add rows and the most recent have to be at indeces 0 and 1? – Gnqz Sep 16 '15 at 22:55
  • How about using sorting? http://stackoverflow.com/questions/9107916/sorting-rows-in-a-data-table – Murray Foxcroft Sep 16 '15 at 22:59
  • @Gnqz after each iteration I want to extend the data in either row A or row B...adding the new value to end of the row...maybe I should have done it at the cell level and added the cell to the row? – John Sep 16 '15 at 23:12

1 Answers1

0

One problem I can see is that each time you are creating a new row/cell instead of getting the reference to an existing row/cell. If I understand correctly, your table has 2 rows, each with 1 cell, and you're trying to grow the contents?

You need to do something more like this. Note that I have not tested this:

TableCell existingCell = myTable.Rows[0].Cells[0];
existingCell.Text += "NewData";

Or if you wanted to add new cells to the existing rows it would be similar:

TableRow existingRow = myTable.Rows[0];
TableCell newCell = new TableCell();
newCell.Text = "NewData";
existingRow.add(newCell);
Ian
  • 1,475
  • 2
  • 15
  • 31
  • this does not work .rows() cant be used like a method in this situation. thanks though – John Sep 17 '15 at 08:16
  • Sorry, I've been doing a lot of VBA recently and that was very similar. .Rows() will return a TableRowCollection. You can use [0] to get an element from that collection. I've updated the example code. – Ian Sep 17 '15 at 12:19