0

I am creating a web app. In my app I have a gridview and a link button inside my gridview. My linkbutton looks like this:

<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("FileData") %>' runat="server" OnClick="lnkDownload_Click"></asp:LinkButton>

In my table there is a link for every file, like(~\userpic\chart.png)

When user clicks on link button the following code should run

protected void lnkDownload_Click(object sender, EventArgs e)
{
    string filePath = (sender as LinkButton).CommandArgument;

    if(string.IsNullOrEmpty(filePath))
    {
        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "", "alert('No File to download.');", true);
        return;
    }
    Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
    Response.WriteFile(filePath);
    Response.End();
}

But when I run the code, I am unable to download the file. When I debug this method, debug breakpoint is not being hit. What is wrong with my code?

2
  • Check the 'Handle click event of linkbutton directly click event code' section of this link: link Commented Feb 13, 2017 at 8:09
  • Post GridView code too. Commented Feb 13, 2017 at 8:31

2 Answers 2

2

on your link button add a CommandName attribute

<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("FileData") %>' runat="server" OnClick="lnkDownload_Click" **CommandName="Download"**></asp:LinkButton>

and on your row command event

  protected void YourGridview_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        { 
           /*your code to download here */
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

1

As you are intended to display this asp:LinkButton inside gridview rows, this OnClick event will not fire. You have to provide OnRowCommand="GridView_RowCommand" attribute for the gridview and write the code for OnClick inside the GridView_RowCommand () method instead of lnkDownload_Click(). I hope this will work. Try it out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.