我在尝试将空行添加到网格视图时遇到索引超出范围异常。这是后面的代码。还有更多列,我只是将它们删除以缩短代码。
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>