user6656728
user6656728

Reputation:

Using link button in a gridview c#

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?

Upvotes: 0

Views: 11134

Answers (2)

MONU THOMAS
MONU THOMAS

Reputation: 13

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.

Upvotes: 1

odlan yer
odlan yer

Reputation: 771

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 */
        }
    }

Upvotes: 2

Related Questions