2012-07-22 57 views
1

我在嘗試向GridView添加空行時遇到索引超出範圍的情況。這是背後的代碼。有更多的列,我只是刪除它們來縮短代碼。向gridview添加行時索引超出範圍

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> 
+0

嘗試更改'For I As Integer = 1 to dtCurrentData.Rows.Count' to'For I As Integer = 0 To dtCurrentData.Rows.Count - 1' – Nalaka526 2012-07-22 17:51:35

+0

仍然在索引超出範圍。 – CodeBrewer 2012-07-22 18:03:51

回答

0

您需要將代碼放入調試中,並查看語句的哪一部分導致異常。

你有兩種可能出現的問題:

  1. 您沒有足夠的行來滿足的rowIndex要求。

  2. 您沒有足夠的單元格來滿足單元格(1)的要求。

我會嘗試改寫這個問題行,如下所示:

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 

您可以設置斷點或拋出異常或任何適合在else子句應用程序時,你沒有你正在期待。