我有GridView
名为 gvEmplAttachments ,有3列:
每行都有一个LinkButton
,允许用户下载文件,该按钮的编码如下:
<asp:LinkButton id="lbViewFile" runat="server" CommandName="ViewFile" CommandArgument='<%# Container.DataItemIndex %>' >View</asp:LinkButton>
使用以下内容设置GridView:
OnRowCommand ="gvEmplAttachments_OpenAttachment_RowCommand"
这样它将执行CodeBehind
中的函数在我的CodeBehind中我有这个功能:
protected void gvEmplAttachments_OpenAttachment_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ViewFile")
{
//Get rowindex
int rowindex = Convert.ToInt32(e.CommandArgument);
//Get the Row
GridViewRow gvr = gvUaSettings.Rows[rowindex];
//Get the Needed Values
Label lblPath = gvr.FindControl("lblFilePath") as Label;
Label lblName = gvr.FindControl("lblFileName") as Label;
//String The values
string fileName = lblName.Text;
string filePath = Server.MapPath(lblPath.Text);
//Should Download the file
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/x-unknown";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.TransmitFile(filePath);
response.Flush();
response.End();
}
}
但问题是当我点击按钮时出现此错误:
对象引用未设置为对象的实例
我的问题是,我错过了什么导致空值。 因为Grid正在显示正确的FileName和FilePath。
答案 0 :(得分:0)
正如您所提到的,您的Gridview ID是 gvEmplAttachments ,但您编写的用于获取触发OnCommand事件的Gridview行的代码具有不同的Gridview ID
GridViewRow gvr = gvUaSettings.Rows[rowindex];
。
您可以尝试使用以下代码来获取行触发命令事件:
GridViewRow gvr = gvEmplAttachments.Rows[rowindex];