Vb.net 向gridview添加行时索引超出范围
我在尝试向gridview添加空行时遇到索引超出范围异常。这就是背后的代码。还有更多的列,我只是删除了它们以缩短代码Vb.net 向gridview添加行时索引超出范围,vb.net,Vb.net,我在尝试向gridview添加空行时遇到索引超出范围异常。这就是背后的代码。还有更多的列,我只是删除了它们以缩短代码 Private Sub AddNewGridRow() Dim rowIndex As Integer = 0 If ViewState("CurrentData") IsNot Nothing Then Dim dtCurrentData As DataTable = DirectCast(ViewState("C
Private Sub AddNewGridRow()
Dim rowIndex As Integer = 0
If ViewState("CurrentData") IsNot Nothing Then
Dim dtCurrentData As DataTable = DirectCast(ViewState("CurrentData"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentData.Rows.Count > 0 Then
For i As Integer = 1 To dtCurrentData.Rows.Count
Dim lblVoucher As Label = DirectCast(GridView1.Rows(rowIndex).Cells(1).FindControl("lblVoucher"), Label)
drCurrentRow = dtCurrentData.NewRow()
drCurrentRow("RecID") = i + 1
dtCurrentData.Rows(i - 1)("RecID") = lblVoucher
rowIndex += 1
Next
dtCurrentData.Rows.Add(drCurrentRow)
ViewState("CurrentData") = dtCurrentData
GridView1.DataBind()
End If
Else
Response.Write("ViewState is null")
End If
SetPreviousData()
End Sub
Private Sub SetPreviousData()
Dim rowIndex As Integer = 0
If ViewState("CurrentData") IsNot Nothing Then
Dim dt As DataTable = DirectCast(ViewState("CurrentData"), DataTable)
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
'Out of range exception happens here when trying to fill the previous data.
Dim lblVoucher As Label = DirectCast(GridView1.Rows(rowIndex).Cells(1).FindControl("lblVoucher"), Label)
lblVoucher.Text = dt.Rows(i)("Voucher").ToString()
rowIndex += 1
Next
End If
End If
End Sub
这是该专栏的aspx
<asp:TemplateField HeaderText="Voucher" SortExpression="RecID">
<HeaderStyle HorizontalAlign="Center" Width="100px" />
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblVoucher" runat="server" Text='<%#Eval("RecID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
您需要将代码放入debug,并查看语句的哪一部分导致异常 您可能有两个问题:
Dim lblVoucher As Label = Nothing
If GridView1.Rows.Count < rowIndex Then
Dim oRow As DataGridViewRow
oRow = GridView1.Rows(rowIndex)
If oRow.Cells.Count > 1 Then
lblVoucher = TryCast(oRow.Cells(1).FindControl("lblVoucher"), Label)
Else
' Do something here when you don't have cells
End If
Else
' Do something here when you don't have a row
End If
Dim lblVoucher As Label=无
如果GridView1.Rows.Count<行索引,则
显示为DataGridViewRow的尺寸
oRow=GridView1.行(行索引)
如果oRow.Cells.Count>1,则
lblVoucher=TryCast(oRow.Cells(1).FindControl(“lblVoucher”),标签)
其他的
“当你没有细胞时,在这里做点什么
如果结束
其他的
“当你没有吵架的时候,在这里做点什么
如果结束
当您没有期望的值时,可以在else子句中设置断点或抛出异常或任何适合您的应用程序的内容。尝试将i As Integer=1的
更改为dtCurrentData.Rows.Count
到对于i As Integer=0到dtCurrentData.Rows.Count-1的索引仍然超出范围。