Click here to Skip to main content
15,902,922 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Why this error Index was out of range. Must be non-negative and less than the size of the collection. in the line given below

GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;


Parameter name: index

my cs code is given below

protected void lkb1_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        string filePath = GridView1.DataKeys[gvrow.RowIndex].Value.ToString();
        Response.ContentType = "image/jpg";
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
        Response.TransmitFile(Server.MapPath(filePath));
        Response.End();
}
Posted
Updated 27-Feb-12 23:22pm
v2
Comments
V. 28-Feb-12 5:22am    
Did you debug?
What does gvrow.RowIndex contain? it should be bigger then -1. It should also be smaller then the size of DataKeys. What is the Count of DataKeys?

GridView1.DataKeys[gvrow.RowIndex].Value.ToString();

A DataKey does not seem to exist for the given RowIndex.
Debugging through your code will help you understand what could be going wrong.
 
Share this answer
 
try this for a "runtime debug":
try
{
string filePath = GridView1.DataKeys[gvrow.RowIndex].Value.ToString();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
 
Share this answer
 
Comments
Janardan Pandey 28-Feb-12 6:09am    
Exception is given - Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
Ank_ush 21-Mar-13 11:25am    
This solution worked as it helped me to trace the proper location of mistake.

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