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
) ON [PRIMARY]

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" "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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <br />
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
        Sales Director Message
    
    </div>
    <asp:Panel ID="Panel1" runat="server" BackColor="#0066FF" Height="132px" 
        Width="788px">
        <asp:Xml ID="Xml1" runat="server" DocumentSource="~/News.xml" 
        TransformSource="~/XSLTFile.xslt"></asp:Xml>
    </asp:Panel>
    <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" />
        <Columns>
            <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" />
        </Columns>
        <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:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:connstr %>" 
        SelectCommand="SELECT * FROM [UserofFile] WHERE ([FileUser] = @FileUser)">
        <SelectParameters>
            <asp:ControlParameter ControlID="userhiddenfield" Name="FileUser" 
                PropertyName="Value" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>
    </form>
</body>
</html>

Open in new window

JeffEaeAsked:
Who is Participating?
 
daveamourCommented:
Ok give it a whirl, should work fine.  Put the full path and filename and extension in there.
0
 
daveamourCommented:
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:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="DownLoadFile" runat="server" NavigateUrl=<%# DataBinder.Eval(Container.DataItem, "DownLoadUrl")%>>Download File</asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>

Open in new window

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

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

 
daveamourCommented:
Ok so in your database do you have a field which stores the location of the file either as a partial url:
/Mydocs/MyFile.jpg
Or c:\inetpub\wwwroot\mysite\mydocs\myfile.jpg
?
0
 
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)
        {
 
            try
            {
                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);
                //run
                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);
        conn.Open();
        int result = cmd.ExecuteNonQuery();
        conn.Close();
        return result;
    }

Open in new window

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