[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Gridview Download problem

Posted on 2009-02-15
9
Medium Priority
?
987 Views
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
) 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

0
Comment
Question by:JeffEae
  • 5
  • 4
9 Comments
 
LVL 19

Expert Comment

by:daveamour
ID: 23647622
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
 

Author Comment

by:JeffEae
ID: 23649971
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
 
LVL 19

Expert Comment

by:daveamour
ID: 23650005
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:JeffEae
ID: 23650047
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
 
LVL 19

Expert Comment

by:daveamour
ID: 23650070
Not a new table - just a new column in your existing table then use that in the NavigateUrl
0
 

Author Comment

by:JeffEae
ID: 23650079
Right, new column I meant
0
 
LVL 19

Accepted Solution

by:
daveamour earned 2000 total points
ID: 23650109
Ok give it a whirl, should work fine.  Put the full path and filename and extension in there.
0
 

Author Comment

by:JeffEae
ID: 23651026
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
 
LVL 19

Expert Comment

by:daveamour
ID: 23656668
Sorry never got a chance to answer that but I assume youve got it working now!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses

873 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