Search code examples
c#asp.netgridviewdownloadlinkbutton

ASP.NET: Download file from database when clicking on file name on Grid View


I have a grid view that displays all of uploaded files of an employee (data from SQL DB).

<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="true" ShowFooter="false" PageSize="5"
CssClass="table" AlternatingRowStyle-BackColor="WhiteSmoke"
HeaderStyle-BackColor="#6C7A95" HeaderStyle-BorderColor="#666666" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="2" HeaderStyle-ForeColor="White"
OnPageIndexChanging="OnPaging" EmptyDataText="No Documents">
    <Columns>
        <asp:BoundField DataField="file_name" HeaderText="File Name" />
        <asp:BoundField DataField="upload_date" HeaderText="Date (GMT -7)" />
        <asp:BoundField DataField="file_status" HeaderText="Status" />

        <asp:TemplateField HeaderText="Employee's Note">
            <ItemTemplate>
                 <a data-original-title='<%# Eval("emp_note")%>' href="#" class="demo-cancel-click" rel="tooltip"><i class="icon-book"></i></a>
             </ItemTemplate>
        </asp:TemplateField>

    </Columns>
</asp:GridView>

The interface look like this: enter image description here

I like to archive this: the file name will be a link button (or whatever the best way is) and when click on name it will download the file. So I modified the File Name column:

<asp:TemplateField HeaderText =" File Name">
        <asp:ItemTemplate>
               <asp:LinkButton ID="lnkDownload" runat="server" 
                    OnClick="DownloadFile" Text='<%#Eval("file_name") %>' 
                    CommandArgument='<%# Eval("file_id") %>'></asp:LinkButton>
         </asp:ItemTemplate>
</asp:TemplateField>

But then the interface became: (file_name disappeared)

enter image description here

How do I get what I need?


Solution

  • You need to remove asp: from ItemTemplate. Your markup should look like below:

    <asp:TemplateField HeaderText=" File Name">
        <ItemTemplate>
            <asp:LinkButton ID="lnkDownload" runat="server"
                OnClick="DownloadFile" Text='<%#Eval("file_name") %>'
                CommandArgument='<%# Eval("file_id") %>'></asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>
    

    Hope it helps!