Gridview Download problem

Posted on 2009-02-15
Last Modified: 2013-11-07

I've got a Gridview that queries a table named FileViewer which is contructed like this:

CREATE TABLE [dbo].[FileViewer](
      [fileid] [int] IDENTITY(1,1) NOT NULL,
      [title] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [subtitle] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [nameoffile] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [date] [datetime] NULL,
      [category] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL

The table corresponds to a file I uploaded to the server earlier.  I've got a download button on each row that is going to then find the file on the server to download it.  What is the easiest/best way to accomplish this?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="User.aspx.cs" Inherits="User" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">

<head runat="server">

    <title>Untitled Page</title>



    <form id="form1" runat="server">



        <br />

        <br />


        Sales Director Message



    <asp:Panel ID="Panel1" runat="server" BackColor="#0066FF" Height="132px" 


        <asp:Xml ID="Xml1" runat="server" DocumentSource="~/News.xml" 



    <br />

    <br />

    <br />

    <br />

    <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">

        <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

Question by:JeffEae
    LVL 19

    Expert Comment

    Use a TemplateField as attached.
    This assumes your file is saved within the browsable web space.  If not then a slightly different technicque will be needed.  Are your files in the web space?

                            <asp:HyperLink ID="DownLoadFile" runat="server" NavigateUrl=<%# DataBinder.Eval(Container.DataItem, "DownLoadUrl")%>>Download File</asp:HyperLink>

    Open in new window


    Author Comment

    Hey dave, the file is saved directly on the web server, if that's what you mean by web space.  I just did something like

    FileUpload1.PostedFile.SaveAs(Server.MapPath(".\\") + fullfilename);

    I have to set the download to find the filename, which is listed on the table and in the gridview that I posted.  
    LVL 19

    Expert Comment

    Ok so in your database do you have a field which stores the location of the file either as a partial url:
    Or c:\inetpub\wwwroot\mysite\mydocs\myfile.jpg

    Author Comment

    No, I guess I have to add a table for that.  Here's  my upload function.  

      protected void uploadbutton_Click(object sender, EventArgs e)
            if (FileUpload1.HasFile)
                    string title = titleuploadtbx.Text;
                    string subtitle = subtitleuploadtbx.Text;
                    string date = dateuploadtbx.txtDate.Text;
                    string filepath = FileUpload1.PostedFile.FileName;
                    string pat = @"\\(?:.+)\\(.+)\.(.+)";
                    Regex r = new Regex(pat);
                    Match m = r.Match(filepath);
                    string filename = m.Groups[1].Captures[0].ToString();
                    string file_ext = m.Groups[2].Captures[0].ToString();
                    string fullfilename = filename + "." + file_ext;
                    string category = CategoryDDL.SelectedItem.Text;
                    FileUpload1.PostedFile.SaveAs(Server.MapPath(".\\") + fullfilename); //filename + "." + file_ext
                    string sql = "insert into FileViewer (title,subtitle,nameoffile,date,category) VALUES ('" + title + "', '" + subtitle + "', '" + fullfilename + "', '" + date + "', '" + category + "')";
                    statusuploadlbl.Text = "Saved to server ";
                    if (InsertToDB(sql) == 1)
                        statusuploadlbl.Text = statusuploadlbl.Text + " And 1 row affected";
                catch (Exception ex)
                    statusuploadlbl.Text = ex.Message;
        public int InsertToDB(string sql)
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ToString());
            SqlCommand cmd = new SqlCommand(sql, conn);
            int result = cmd.ExecuteNonQuery();
            return result;

    Open in new window

    LVL 19

    Expert Comment

    Not a new table - just a new column in your existing table then use that in the NavigateUrl

    Author Comment

    Right, new column I meant
    LVL 19

    Accepted Solution

    Ok give it a whirl, should work fine.  Put the full path and filename and extension in there.

    Author Comment

    Ok so I've got a new variable in my upload function and added a new table to my db called 'filepath'

    filepath = Server.MapPath(".\\") + fullfilename;

    How do I pass this into the template field?
    LVL 19

    Expert Comment

    Sorry never got a chance to answer that but I assume youve got it working now!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
    A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now