C# '中的服务器错误/网站8';应用索引超出范围。必须为非负数且小于集合的大小。参数名称:索引

C# '中的服务器错误/网站8';应用索引超出范围。必须为非负数且小于集合的大小。参数名称:索引,c#,asp.net,C#,Asp.net,说明: System.Argument Out Of Range Exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index protected void ImageButton1_Click (object sender, EventArgs e) { ImageButton lnkb

说明:

System.Argument Out Of Range Exception: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  protected void ImageButton1_Click (object sender, EventArgs e)

    {
        ImageButton lnkbtn = sender as ImageButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        
        
           string filePath = GridView2.DataKeys[gvrow.RowIndex].Value.ToString();

            Response.ContentType = "image/jpg";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
            Response.TransmitFile(Server.MapPath(filePath));
            Response.End();
        
    }
执行当前web请求期间发生异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源

异常详细信息:

System.Argument Out Of Range Exception: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  protected void ImageButton1_Click (object sender, EventArgs e)

    {
        ImageButton lnkbtn = sender as ImageButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        
        
           string filePath = GridView2.DataKeys[gvrow.RowIndex].Value.ToString();

            Response.ContentType = "image/jpg";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
            Response.TransmitFile(Server.MapPath(filePath));
            Response.End();
        
    }
代码:

System.Argument Out Of Range Exception: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
  protected void ImageButton1_Click (object sender, EventArgs e)

    {
        ImageButton lnkbtn = sender as ImageButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        
        
           string filePath = GridView2.DataKeys[gvrow.RowIndex].Value.ToString();

            Response.ContentType = "image/jpg";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
            Response.TransmitFile(Server.MapPath(filePath));
            Response.End();
        
    }

在我看来,在这一点上你们面临着这个问题

string filePath = GridView2.DataKeys[gvrow.RowIndex].Value.ToString();
尝试提取datakey的值时,GVrow.RowIndex的值大于元素计数


尝试调试并查看元素的计数以及gvrow.RowIndex设置的内容。

gvrow.RowIndex
可能为-1,因为未选择该行以获取值