0

我有一个带有按钮的 asp.net 页面,该按钮向 gridview 添加额外的行以输入数据库。网格视图由 3 个文本框(模板字段)组成,当我添加一行时,已经输入的信息会以某种方式在回发中消失。我希望按钮添加其他行而不消除其他行中的数据,直到我点击提交按钮。这是我的代码

Private Sub AddNewRowToGrid()
    Dim rowIndex As Integer = 0
    If ViewState("CurrentTable") IsNot Nothing Then
        Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
        Dim drCurrentRow As DataRow = Nothing
        If dtCurrentTable.Rows.Count > 0 Then
            For i As Integer = 1 To dtCurrentTable.Rows.Count
                'extract the TextBox values
                Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
                Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
                Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
                drCurrentRow = dtCurrentTable.NewRow()
                drCurrentRow("Approval Date") = box1.ToString
                dtCurrentTable.Rows(i - 1)("Total Amount") = box2.ToString
                dtCurrentTable.Rows(i - 1)("Comments") = box3.ToString
                'dtCurrentTable.Rows(i - 1)("Initials") = 
                rowIndex += 1
            Next
            dtCurrentTable.Rows.Add(drCurrentRow)
            ViewState("CurrentTable") = dtCurrentTable
            gvOLIAdj.DataSource = dtCurrentTable
            gvOLIAdj.DataBind()
        End If
    Else
        Response.Write("ViewState is null")
    End If
    'Set Previous Data on Postbacks
    'SetPreviousData()
End Sub

Private Sub SetPreviousData()
    Dim rowIndex As Integer = 0
    If ViewState("CurrentTable") IsNot Nothing Then
        Dim dats As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
        If dats.Rows.Count > 0 Then
            For i As Integer = 0 To dats.Rows.Count - 1
                Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
                Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
                Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
                box1.Text = dats.Rows(i)("Approval Date").ToString()
                box2.Text = dats.Rows(i)("Total Amount").ToString()
                box3.Text = dats.Rows(i)("Comments").ToString()
                rowIndex += 1
            Next
        End If
    End If
End Sub
4

1 回答 1

0

I can think of two reasons why this may be happening:

  1. When you create controls dynamically it is VERY difficult to retrieve the values in the code behind after postback
  2. Your controls have the read-only attribute set in the raw HTML

You may want to try old-fashioned methods such as Request.Form http://msdn.microsoft.com/en-us/library/ms525985%28v=vs.90%29.aspx

于 2012-05-11T23:09:26.190 回答