Click here to Skip to main content
15,888,106 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I tring to retrieve pdf or any file from sql database but I got error Index was out of range. Must be non-negative and less than the size of the collection

What I have tried:

ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <columns>
        <asp:BoundField DataField="Section" HeaderText="File Name" />
        <asp:BoundField DataField="Category" HeaderText="File Name" />
        <asp:TemplateField ItemStyle-HorizontalAlign="Center">
            <itemtemplate>
               
                 <asp:LinkButton ID="lnkView" OnClick="OpenDocument" runat="server" Text='<%# Eval("Link") %>'>

C#
protected void OpenDocument(object sender, EventArgs e)
{
    LinkButton lnk = (LinkButton)sender;
    GridViewRow gr = (GridViewRow)lnk.NamingContainer;
    if (gr.RowIndex > 0)
    { 
    int id = int.Parse(GridView1.DataKeys[gr.RowIndex].Value.ToString());
    Download(id);
    }
}
private void Download(int id)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["IntranetConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT Seqn, Section, Category, Link from Links WHERE Seqn = @seqn ";
            cmd.Connection = con;
            cmd.Parameters.Add("@seqn", SqlDbType.Int).Value = id;
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            dt.Load(reader);
        }
    }
    string name = dt.Rows[0]["Category"].ToString();
    byte[] documentBytes = (byte[])dt.Rows[0]["Link"];
    Response.ClearContent();
    Response.ContentType = "application/octetstream";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename={}", name));
    Response.AddHeader("Content-Length", documentBytes.Length.ToString());

    Response.BinaryWrite(documentBytes);
    Response.Flush();
    Response.Close();
 }
private void FillData()
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["IntranetConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT Seqn, Section, Category, Link from Links ";
            cmd.Connection = con;
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
           
            dt.Load(reader);
          
            con.Close();
        }
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}
Posted
v2
Comments
Richard Deeming 17-Nov-16 13:03pm    
Were you planning to tell us which line of that code the exception is thrown from?
j snooze 17-Nov-16 17:26pm    
How come you check the data row count in FillData, but not Download seems to me you are assuming data is coming back in the Download method and telling it to access Row [0]...if there is no data your index is out of bounds. Just a thought.
Karthik_Mahalingam 17-Nov-16 22:54pm    
use debugger to find the line where the error is thrown

Member 12856488 wrote:
int id = int.Parse(GridView1.DataKeys[gr.RowIndex].Value.ToString());

check the datakeys count
 
Share this answer
 
v2
C#
on whichh line you are getting error?
first need to check datakey and then rowindex.
and these two are ok then check final id which you are passing to download function.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900