Gridview Download problem

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

Who is Participating?
Ok give it a whirl, should work fine.  Put the full path and filename and extension in there.
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

JeffEaeAuthor Commented:
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.  
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

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
JeffEaeAuthor Commented:
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

Not a new table - just a new column in your existing table then use that in the NavigateUrl
JeffEaeAuthor Commented:
Right, new column I meant
JeffEaeAuthor Commented:
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?
Sorry never got a chance to answer that but I assume youve got it working now!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.