tags:

views:

30

answers:

1

I am building an ASP.NET application that needs dynamic tables. That's another issue that I've already posted about (and gotten a pretty good response!). Now, I'm running into another issue - I want to add new rows to my table, but given that I will have 10-12 tables on one page, each containing different objects in their rows (text boxes, check boxes, etc.) I need a way of simply generically adding a new row that has the same objects as the first row in the table. Here's my code:

Private Sub AddTableRow(ByRef originalTable As System.Web.UI.WebControls.Table)

        Dim originalRow As System.Web.UI.WebControls.TableRow = originalTable.Rows(1)
        Dim insertingRow As New System.Web.UI.WebControls.TableRow
        Dim insertingCells(originalRow.Cells.Count) As System.Web.UI.WebControls.TableCell
        Dim index As Integer = 0

        For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells

            insertingCells(index) = New System.Web.UI.WebControls.TableCell
            insertingCells(index).Controls.Add(cell.Controls.Item(0))

            index += 1
        Next

        insertingRow.Cells.AddRange(insertingCells)

        originalTable.Rows.Add(insertingRow)

    End Sub

But I'm getting a null reference exception at the second to last line,

insertingRow.Cells.AddRange(insertingCells)

...and I can't figure out why. Is it because the contents of each cell are not being initialized with a new object? If so, how would I get around this?

Thanks!

EDIT:

The inside of my for loop now looks like this -

For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
        Dim addedContent As New Object
        Dim underlyingType As Type = cell.Controls.Item(0).GetType

        addedContent = Convert.ChangeType(cell.Controls.Item(0), underlyingType)
        insertingCells(index) = New System.Web.UI.WebControls.TableCell
        insertingCells(index).Controls.Add(addedContent)

        index += 1
Next

Stepping through with a debugger, I see that this strategy is working - but the additional table row still doesn't appear...and still does when I do this statically.

+1  A: 

I think your culprit may be this line:

Dim insertingCells(originalRow.Cells.Count) As TableCell

Confusingly, the number you specify in an array declaration in VB.NET is the upper bound, not the number of elements. So Dim ints(10) As Integer will create an Integer() array with eleven elements, not ten (10 will be the highest index of the array).

Try this instead:

Dim insertingCells(originalRow.Cells.Count - 1) As TableCell
Dan Tao
That solved the runtime error issue, but apparently objects are still not being copied - no new row is added to my table. I commented out that code and plugged in a static addition of a table row, and a new row was then added to my table.Something is still amiss here. Thanks for your help so far! =)
Ryan