We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now


Download buttons on gridview problem

JeffEae asked
Medium Priority
Last Modified: 2013-12-17
Hi, I'm having trouble getting my Download column on my gridview to work.  I have an upload function in my program that saves all the files to the server, along with inserting the filepath, filename, and other things into the database.  On my user page (see the attached screenshot), I've got a gridview with columns with a download button.  One column is the filename.  I figure this should be straight forward, setting the download up to download the name of the file in the same row, but I just can't figure out programmatically what I would do to get the value of each filename in the row and then do some sort of Response.Transferfile(file_name_in_the_row).  Hopefully I'm clear, please feel free to ask if I left something out.  
<asp:HiddenField ID="userhiddenfield" runat="server" />
         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" 
        GridLines="None" style="margin-right: 0px" Width = "1000px">
        <RowStyle BackColor="#EFF3FB" />
            <asp:ButtonField ButtonType="Button" Text="Download" />
            <asp:BoundField DataField="fileid" HeaderText="ID" 
                SortExpression="fileid" />
            <asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
            <asp:BoundField DataField="subtitle" HeaderText="Subtitle" 
                SortExpression="subtitle" />
            <asp:BoundField DataField="nameoffile" HeaderText="File Name" 
                SortExpression="nameoffile" />
            <asp:BoundField DataField="date" HeaderText="Date" SortExpression="Date" />
            <asp:BoundField DataField="category" HeaderText="Category" 
                SortExpression="category" />
            <asp:BoundField DataField="FileUser" HeaderText="User" 
                SortExpression="FileUser" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" BorderColor="#0033CC" Font-Bold="True" 
            ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:connstr %>" 
        SelectCommand="SELECT * FROM [UserofFile] WHERE ([FileUser] = @FileUser)" 
            <asp:ControlParameter ControlID="userhiddenfield" Name="FileUser" 
                PropertyName="Value" Type="String" />

Open in new window

Watch Question

Top Expert 2009

Why can't you just add a hyperlink to this download column and provide the file path there?

So instead of:
<asp:ButtonField ButtonType="Button" Text="Download" />

you'll have:

<asp:Hyperlink ID="FileDownloadLink" runat="server" NavigateUrl="provide the file path here" Text="Download" />


Alright, so if I uploaded the documents using Server.MapPath(".\\"), what would the navigateUrl be? And then I still need to get the filename, which is in its own column in the row of the download link.  
Top Expert 2009

The NavigateUrl will be a relative path on the server (or you could hardcode the path from a different server). Try something like this:

<asp:HyperLink ID="downloadLink" runat="server" NavigateUrl='<%# GetFilePath(DataBinder.Eval(Container, "DataItem.Download").ToString())%>' />
and in your code-behind file:
public string GetFilePath(string Download)
    string path = Server.MapPath("//");
    string filePath = string.Format("{0}//{1}", path, Download);
    return filePath;

Open in new window


I tried to insert that Hyperlink instead of the Button and got

Error      1      System.Web.UI.WebControls.DataControlFieldCollection must have items of type 'System.Web.UI.WebControls.DataControlField'. 'asp:HyperLink' is of type 'System.Web.UI.WebControls.HyperLink'.      C:\Documents and Settings\Datalis\My Documents\Visual Studio 2008\WebSites\USCorrugatedtool\User.aspx      21      

And where am I returning the file name from the column named 'filename' on the corresponding row?

You can use template of gridview. 

Instead of this
/><asp:ButtonField ButtonType="Button" Text="Download" />

Use as below.

Open in new window

                        <asp:HyperLink runat="Server" ID="hlDownload" NavigateUrl='<%# Eval("RelativeFilePath") %>'></asp:HyperLink>

Open in new window


Try This


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DownLoad.aspx.vb" Inherits="FileDownload_DownLoad" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <asp:BoundField DataField="FileName" HeaderText="FileName" ReadOnly="True" SortExpression="FileName" />
                <asp:TemplateField HeaderText="Download" >
                  <asp:HyperLink       runat="server" ID="aaa"      />  


Imports System.Data
Partial Class FileDownload_DownLoad
    Inherits System.Web.UI.Page
    Private Function GetData() As DataTable
        Dim dt As New DataTable
        dt.Rows.Add(New Object() {"TextFile.txt", "TextFile.txt"})
        dt.Rows.Add(New Object() {"TextFile1.txt", "TextFile1.txt"})
        Return dt
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            Me.GridView1.DataSource = GetData()
        End If
    End Sub


    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim ctrl As HyperLink
        If e.Row.RowType = DataControlRowType.DataRow Then
            ctrl = CType(e.Row.Controls(1).Controls(1), HyperLink)
            ctrl.NavigateUrl = e.Row.Cells(0).Text
            ctrl.Text = e.Row.Cells(0).Text

        End If
    End Sub
End Class


The problem of which template to use is fine, I'll go with what bedanand:said and use a link instead of a button.  Taking a look at my screenshot, the column 'filename' is where I'm stuck.  I know there has to be a way to get the hyperlink to actually read that filename in the row that it is in and then download.  


Anybody? This project is almost done, this is my last piece! =P
If you have already saved the relative filepath on the database table on single columns just put the column name

                        <asp:HyperLink runat="Server" ID="hlDownload" NavigateUrl='<%# Eval("FilePath") %>'></asp:HyperLink>

If you have put on two or more columns you can concate the fields

like this

                        <asp:HyperLink runat="Server" ID="hlDownload" NavigateUrl='<%# Eval("FilePath") + Eval("FileName") %>'></asp:HyperLink>

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts


The last person had the right answer, after I opened the delete request
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.