我在点击gridvioew中的下载按钮时遇到以下错误 指数超出范围。必须是非负数且小于集合的大小。 参数名称:index 我的aspx代码是
<asp:GridView ID ="gvDetails" runat ="server" AutoGenerateColumns="False" >
<Columns >
<asp:BoundField DataField ="auto_id" ReadOnly ="True" HeaderText="Sr No." />
<asp:BoundField DataField ="topic_name" ReadOnly ="True" HeaderText ="Announcement" />
<asp:TemplateField HeaderText ="File Path">
<ItemTemplate >
<asp:LinkButton ID ="lnkDownload" runat ="server" Text="Download" OnClick="lnkDownload_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
my code for downloading is
protected void lnkDownload_Click(object sender, EventArgs e)
{
try
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int field = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value .ToString ());
SqlDataReader dr = MclsAssignment.getDownload(field);
if (dr.Read())
{
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["mfile_name"] + "\"");
Response.BinaryWrite((byte[])dr["file_data"]);
Response.End();
}
}
catch (Exception)
{
throw;
}
}
答案 0 :(得分:0)
如果未选择任何行,您将收到异常。因此,您需要检查
gvrow.RowIndex
大于-1。
protected void lnkDownload_Click(object sender, EventArgs e)
{
try
{
if(gvrow.RowIndex < 0) //return if user hasn't selected any row
return;
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int field = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value .ToString ());
SqlDataReader dr = MclsAssignment.getDownload(field);
if (dr.Read())
{
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["mfile_name"] + "\"");
Response.BinaryWrite((byte[])dr["file_data"]);
Response.End();
}
}
catch (Exception)
{
throw;
}
}
答案 1 :(得分:0)
我认为你必须检查gvRow.RowIndex为-1。如果用户没有在gridview中选择一行,它将为您提供例外。
答案 2 :(得分:0)
<asp:LinkButton ID ="lnkDownload" runat ="server" Text="Download" RowIndex='<%# Container.DisplayIndex %>' OnClick="lnkDownload_Click" ></asp:LinkButton>
---------------------------------------------------------------
int field = Convert.ToInt32(lnkbtn.Attributes["RowIndex"]);
希望这会让你获得rowIndex但是如果你遇到问题请详细说明你的问题并确切地说明你在哪里得到错误?
但是使用Command事件会更有效率。
答案 3 :(得分:0)
请尝试Row Command事件,这是您问题的最简单的解决方案
实施例
<asp:GridView ID ="gvDetails" runat ="server" AutoGenerateColumns="False" >
<Columns >
<asp:BoundField DataField ="auto_id" ReadOnly ="True" HeaderText="Sr No." />
<asp:BoundField DataField ="topic_name" ReadOnly ="True" HeaderText ="Announcement" />
<asp:TemplateField HeaderText ="File Path">
<ItemTemplate >
<asp:LinkButton ID ="lnkDownload" runat ="server" Text="Download" CommandName="Download" CommandArgument='<%#Eval("YourID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "application")
{
// write your code
}
}