2010-07-29 54 views
0

這裏是我到目前爲止,代碼明智:如何動態地向表中添加多行是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 

...但它只能動態地添加一行。第一次添加之後,點擊更多按鈕將不會添加更多行。任何想法爲什麼?更好的方式來做到這一點?

+0

什麼是tbl7,它是否啓用了ViewState? – 2010-07-29 15:54:32

+0

對不起 - tbl7是在ASP代碼中聲明的表 - 這是背後的VB代碼。是的,ViewState已啓用。 – rybosome 2010-07-29 15:57:25

+0

你的Page_Load事件中有什麼? – 2010-07-29 15:59:40

回答

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

+0

我認爲這可能是最好的解決方案......雖然這將會變得非常複雜。這一頁將有14個左右的表格。無論如何,感謝您的幫助 - 這是我需要開始的! – rybosome 2010-07-29 17:21:27

0

HtmlTable似乎沒有任何種類的ViewState感知,因此無論是在每次回發中構建所有行,還是使用asp:Table或者asp:Repeater代替。