2010-07-29 14 views
0

我正在構建需要動態表的ASP.NET應用程序。這是我已經發布的另一個問題(並得到了相當不錯的迴應!)。現在,我遇到了另一個問題 - 我想添加新行到我的表中,但考慮到我將在一個頁面上有10-12個表格,每個表格都包含行中的不同對象(文本框,複選框等)。 )我需要一種簡單的方式來一般添加一個與表中第一行具有相同對象的新行。這裏是我的代碼:如何在VB.NET中複製對象類型?

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 

但我發現了在倒數第二行一個空引用異常,

insertingRow.Cells.AddRange(insertingCells)

,我還可以」弄清楚爲什麼。是否因爲每個單元格的內容沒有使用新對象進行初始化?如果是這樣,我將如何解決這個問題?

謝謝!

編輯:

我的for循環,現在看起來是這樣的內部 -

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 

步進通過與調試器,我看到這個策略是工作 - 但附加錶行仍然沒有按」 t出現...並且當我靜態地做這件事時仍然會這樣。

回答

1

我想你的罪魁禍首可能是這一行:

Dim insertingCells(originalRow.Cells.Count) As TableCell 

令人困惑的是,您在VB.NET數組聲明中指定的數量上限,而不是元素的個數。因此,Dim ints(10) As Integer將創建一個Integer()陣列與十一元素,而不是十(10將是陣列的最高索引)。

試試這個:

Dim insertingCells(originalRow.Cells.Count - 1) As TableCell 
+0

這解決了運行時錯誤的問題,但顯然對象仍然沒有被複制 - 沒有新的行被添加到我的餐桌。我註釋掉了那些代碼並插入了一個表格行的靜態添加,然後一個新行添加到了我的表格中。 這裏有些東西仍然不對。感謝您一直以來的幫助! =) – rybosome 2010-07-29 18:42:02