0

我有一个GridView名为gvEmplAttachments的 3 列:

  • ID
  • 文件名
  • 文件路径

每行都有一个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。

在此处输入图像描述

4

1 回答 1

0

正如您提到的,您的 Gridview ID 是gvEmplAttachments,但是您编写的用于获取触发 OnCommand 事件的 Gridview 行的代码具有不同的 Gridview ID GridViewRow gvr = gvUaSettings.Rows[rowindex];

您可以尝试使用以下代码来获取行触发命令事件:

GridViewRow gvr = gvEmplAttachments.Rows[rowindex];

于 2017-09-27T12:33:36.030 回答