Search code examples
c#asp.netgridviewresponse.transmitfile

File not downloading from GridView on click event


I have a GridView named gvEmplAttachments that has 3 columns:

  • id
  • FileName
  • FilePath

Each row has a LinkButton that will allows the user to download the file, that button is coded as such:

<asp:LinkButton  id="lbViewFile" runat="server" CommandName="ViewFile" CommandArgument='<%# Container.DataItemIndex %>' >View</asp:LinkButton>

The GridView is set with the following:

OnRowCommand ="gvEmplAttachments_OpenAttachment_RowCommand"

So that it will execute the function in the CodeBehind


In my CodeBehind I have this function:

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();
    }
}

But the problem is when I click the button I get this error:

Object reference not set to an instance of an object

My question is, what am I missing that would be causing the null value. Because the Grid is displaying the correct FileName and FilePath.

enter image description here


Solution

  • As you mentioned your Gridview ID is gvEmplAttachments, but the code you written to grab the row of Gridview which trigger OnCommand event is having different Gridview ID GridViewRow gvr = gvUaSettings.Rows[rowindex];.

    You can try for the following Code to fetch the row triggering command event:

    GridViewRow gvr = gvEmplAttachments.Rows[rowindex];