Index Out of Range Exception on GridView1.SelectedIndex

36 Views Asked by At

I have been trying to resolve this issue for days with no result. I saw many posts on StackOverflow relating to this issue but couldn't get anything to work.

In my GridView1_SelectedIndexChanged function I don't get index out of range but when I try to access a selected row in another function I get the error. Another thing is that when I click select on the gridview the whole grid disappears.

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            ' Only add the event handler on initial page load
            AddHandler GridView1.SelectedIndexChanged, AddressOf GridView1_SelectedIndexChanged
            GridView1.DataBind()
        End If
    End Sub

   'Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
    '    Try
    '        If GridView1.SelectedIndex <> -1 Then
    '            UpdateButtonVisibility()
    '            Dim itemSelected As GridViewRow = GridView1.SelectedRow
    '            Dim acoo As String = itemSelected.Cells(1).Text

    '            Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ExtranetConnectionString").ConnectionString)
    '            Dim query As String = "Select InvoiceAttach FROM TblInvoice WHERE CertificateId=@acoo"

    '            Using sqlCmd As New SqlCommand(query, conn)
    '                sqlCmd.Parameters.Add(New SqlParameter("acoo", acoo))
    '                conn.Open()

    '                Dim reader As SqlDataReader = sqlCmd.ExecuteReader()

    '                If reader.HasRows Then
    '                    reader.Read()
    '                    'url = "/Files/" & reader("InvoiceAttach")
    '                    url = reader("InvoiceAttach") & ""
    '                    Dim s As String = "window.open('" & url + "', 'popup_window', 'width=500,height=800,left=100,top=100,resizable=yes');"
    '                    ClientScript.RegisterStartupScript(Me.GetType(), "script", s, True)

    '                End If
    '              
    '            End Using
    '        End If
    '    Catch ex As Exception
    '        MsgBox(ex.Message)
    '    End Try
    '    GridView1.DataBind()
    'End Sub

The following is what I have in the frontend:

  <asp:GridView ID="GridView1" runat="server" CssClass="table" EnableViewState="true" AutoGenerateColumns="False" AutoPostBack="True" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:CommandField ShowSelectButton="True" />
                    <asp:BoundField DataField="Acoo" HeaderText="Acoo" InsertVisible="False" ReadOnly="True" SortExpression="Acoo" />
                    <asp:BoundField DataField="Tp" HeaderText="Tp" SortExpression="Tp" />
                    <asp:BoundField DataField="Idno" HeaderText="Idno" SortExpression="Idno" />
                    <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
                    <asp:BoundField DataField="invoicenumber" HeaderText="invoicenumber" SortExpression="invoicenumber" />
                    <asp:BoundField DataField="invoicedate" HeaderText="invoicedate" SortExpression="invoicedate" />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ExtranetConnectionString %>" SelectCommand="SELECT Acoo, Tp, Idno, Status, invoicenumber, invoicedate FROM TblACOO WHERE (Status = 4) AND (Tp = @Tp) AND (Idno = @Idno) ORDER BY invoicedate DESC">
                <SelectParameters>
                    <asp:FormParameter FormField="type" Name="Tp" Type="Int32" />
                    <asp:FormParameter FormField="idno" Name="Idno" Type="Int32" />
                </SelectParameters>
            </asp:SqlDataSource>

The above function for GridView1_SelectedIndexChanged works fine and SelectedRow gets a value but when I try the bottom code or when I try to access GridView1.SelectedRow in another function I get Index out of range exception. I think it has to do with the GridView disappearing on PostBack, even when I rebind the GridView.

    Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
        Try
            If GridView1.SelectedIndex <> -1 Then
                UpdateButtonVisibility()
                GridView1.DataBind()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Function GetInvoiceAttachUrl(acoo As String) As String
        ' Retrieve the URL from the database based on the CertificateId
        Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("ExtranetConnectionString").ConnectionString)
        Dim query As String = "Select InvoiceAttach FROM TblInvoice WHERE CertificateId=@acoo"

        Using sqlCmd As New SqlCommand(query, conn)
            sqlCmd.Parameters.Add(New SqlParameter("acoo", acoo))
            conn.Open()

            Dim reader As SqlDataReader = sqlCmd.ExecuteReader()

            If reader.HasRows Then
                reader.Read()
                Return reader("InvoiceAttach").ToString()
            End If
        End Using

        Return String.Empty
    End Function

    Private Sub OpenPdfInNewWindow(url As String)
        ' Open the PDF in a new browser window
        Dim script As String = "window.open('" & url + "', 'popup_window', 'width=800,height=600,left=100,top=100,resizable=yes');"
        ClientScript.RegisterStartupScript(Me.GetType(), "OpenPdfScript", script, True)
    End Sub


    Private Sub UpdateButtonVisibility()
        Button1.Visible = GridView1.SelectedIndex <> -1
        Button2.Visible = GridView1.SelectedIndex <> -1
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            If GridView1.SelectedIndex <> -1 Then
                Dim itemSelected As GridViewRow = GridView1.SelectedRow
                Dim acoo As String = itemSelected.Cells(1).Text


                ' Retrieve the URL
                Dim url As String = GetInvoiceAttachUrl(acoo)

                If Not String.IsNullOrEmpty(url) Then
                    ' Open the PDF in a new window
                    OpenPdfInNewWindow(url)
                Else
                    ' Handle the case where no URL is found (e.g., display a message)
                    MsgBox("No PDF URL found for the selected item.")
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

The error occurs on the line Dim itemSelected As GridViewRow = GridView1.SelectedRow

0

There are 0 best solutions below