如何动态地向表中添加多行是ASP.NET?

时间:2010-07-29 15:50:09

标签: asp.net

到目前为止,这是代码方面的内容:

Protected Sub btnAddRow7_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddRow7.Click

    Dim tableRow As New System.Web.UI.WebControls.TableRow
    Dim tableCell As New System.Web.UI.WebControls.TableCell
    Dim textBox As New System.Web.UI.WebControls.TextBox

    tableCell.Controls.Add(textBox)

    tableRow.Cells.Add(tableCell)

    tbl7.Rows.Add(tableRow)

End Sub

...但它只是动态添加一行。首次添加后,对按钮的更多点击将不会添加更多行。知道为什么吗?更好的方法吗?

2 个答案:

答案 0 :(得分:0)

HtmlTable似乎没有任何类型的ViewState感知,因此要么在每次回发时构建所有行,要么使用asp:Table或asp:Repeater。

答案 1 :(得分:0)

您可以在Page.Load中重建您的表格。例如:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    rebuildMyTable()
End Sub

Private Sub rebuildMyTable()
    If Me.ViewState("TableRowCount") Is Nothing Then Me.ViewState("TableRowCount") = 0
    For i As Int32 = 0 To CInt(Me.ViewState("TableRowCount")) - 1
        AddTableRow()
    Next
End Sub

Private Sub AddTableRow()
    Dim tableRow As New System.Web.UI.WebControls.TableRow
    Dim tableCell As New System.Web.UI.WebControls.TableCell
    Dim textBox As New System.Web.UI.WebControls.TextBox

    tableCell.Controls.Add(textBox)

    tableRow.Cells.Add(tableCell)

    Me.MyTable.Rows.Add(tableRow)
End Sub

Protected Sub BtnAddRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAddRow.Click
    AddTableRow()

    If Me.ViewState("TableRowCount") Is Nothing Then
        Me.ViewState("TableRowCount") = 1
    Else
        Me.ViewState("TableRowCount") = CInt(Me.ViewState("TableRowCount")) + 1
    End If
End Sub

这是因为按钮事件在Viewstate注册后出现。 http://msdn.microsoft.com/en-us/library/ms178472.aspx