文本框值在回发时消失

时间:2012-05-11 20:24:29

标签: asp.net vb.net gridview

我有一个带有按钮的asp.net页面,该按钮可以向gridview添加一行以输入数据库。 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

1 个答案:

答案 0 :(得分:0)

我可以想到可能发生这种情况的两个原因:

  1. 动态创建控件时非常困难 在回发后检索后面代码中的值
  2. 您的控件具有在原始HTML中设置的只读属性
  3. 您可能想尝试一些老式方法,例如Request.Form http://msdn.microsoft.com/en-us/library/ms525985%28v=vs.90%29.aspx