1

グリッドビューに空の行を追加しようとすると、範囲外のインデックスが発生します。これがコードビハインドです。さらに列があります。コードを短くするためにそれらを削除しました。

   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>
4

1 に答える 1

0

コードをデバッグして、ステートメントのどの部分が例外を引き起こしているかを確認する必要があります。

考えられる問題は2つあります。

  1. rowIndex要件を満たすのに十分な行がありません。

  2. cells(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句でブレークポイントを設定したり、例外をスローしたり、アプリケーションに適したものをスローしたりできます。

于 2012-07-22T18:56:10.727 に答える