我正在尝试将新行添加到gridview中但由于某种原因我在for循环中遇到了问题。
直接转到 dtCurrentTable.Rows.Add(drCurrentRow)当然有错误“'row'参数不能为null。参数名称:row”,因为 dtcurrentTable.NewRow 未执行。
为什么会这样?
Private Sub AddNewRowToGrid()
Dim rowIndex As Integer = 0
If Not IsNothing(ViewState("CurrentTable")) Then
Dim dtCurrentTable As DataTable = CType(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
For i as Integer = 1 To i <= dtCurrentTable.Rows.Count
' Extraem-se os valores das Textbox
Dim box1 As TextBox = Dados.Rows(rowIndex).Cells(0).FindControl("Artigo")
Dim box2 As TextBox = Dados.Rows(rowIndex).Cells(1).FindControl("Descricao")
Dim box3 As TextBox = Dados.Rows(rowIndex).Cells(2).FindControl("IVA")
Dim box4 As TextBox = Dados.Rows(rowIndex).Cells(3).FindControl("PU")
Dim box5 As TextBox = Dados.Rows(rowIndex).Cells(4).FindControl("Desconto")
Dim box6 As TextBox = Dados.Rows(rowIndex).Cells(5).FindControl("UN")
Dim box7 As TextBox = Dados.Rows(rowIndex).Cells(6).FindControl("Quantidade")
Dim box8 As TextBox = Dados.Rows(rowIndex).Cells(7).FindControl("TotalLiquido")
drCurrentRow = dtCurrentTable.NewRow
dtCurrentTable.Rows(i - 1)("Artigo") = box1.Text
dtCurrentTable.Rows(i - 1)("Descricao") = box2.Text
dtCurrentTable.Rows(i - 1)("IVA") = box3.Text
dtCurrentTable.Rows(i - 1)("PU") = box4.Text
dtCurrentTable.Rows(i - 1)("Desconto") = box5.Text
dtCurrentTable.Rows(i - 1)("UN") = box6.Text
dtCurrentTable.Rows(i - 1)("Quantidade") = box7.Text
dtCurrentTable.Rows(i - 1)("TotalLiquido") = box8.Text
rowIndex += 1
Next i
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentTable") = dtCurrentTable
Dados.DataSource = dtCurrentTable
Dados.DataBind()
End If
Else
Response.Write("ViewState null")
End If
SetPreviousData()
End Sub
答案 0 :(得分:0)
您的For
循环定义错误,这就是您收到错误的原因:
For i as Integer = 1 To i <= dtCurrentTable.Rows.Count
评估为
For i as Integer = 1 To True
(因为我总是&lt; = Rows.Count)
VB翻译为
For i as Integer = 1 To -1
这意味着你的循环永远不会运行。
有 应该是
For i as Integer = 1 To dtCurrentTable.Rows.Count
此外,您使用drCurrentRow = dtCurrentTable.NewRow
的方式有些奇怪。当你在循环中不对它做任何事情时,为什么在循环内?它被执行多次,然后dtCurrentTable.Rows.Add(drCurrentRow)
只被调用一次。
我很难纠正,因为我无法弄清楚你想要做什么,但这一点看起来很狡猾。