Download a file from sql (doc, txt, xls, pdf) files available in the db to be displayed in a datagrid, gridview, ...

Every search that I come up with is wanting to save the results displayed in the datagrid.  My page would be a list of all documents stored in the database.  Actually what is stored in the database is just a webpath on the server.

My sql table has for columns - DocsID , ProjectID, Title, Webpath

I was looking for a grid that looked something like this: 

                                  DocsID    ProjectID                    Title                                       Webpath

 Click Me to Download:    1 ,            32,                  My I love SQL.pdf                       C:/servertarget

 Click Me to Download:    2 ,            32,           Why does my hair fall out?.doc,          C:/servertarget

Do I just want to make a datagrid and put a hyperlink on the Webpath field?

Would someone mind giving me a hand in code?  I would appreciate it - See DocsID # 2 as a reference :-(     b/c I'm quite fond of my hair 

Thanks much!!


Call me $wank
0
Swank
4/8/2009 2:43:47 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

7 Replies
2446 Views

Similar Articles

[PageSpeed] 3

The easiest way to do this is to just have a varchar field in SQL that stores the entire file location. Then in your datagrid you can generate a hyperlink column using the stored value.

-1
TommyGunn32
4/8/2009 3:43:07 PM

You can do like this...

<asp:GridView ID="grdv" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Title" >

<ItemTemplate>

<asp:LinkButton ID="lnkPath" runat="server" Text= '<%# Bind("Coach_First") %>' OnClick="lnkPath_OnClick" ></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="DocsID" >

<ItemTemplate>

<asp:Label ID="lblDocsID" runat="server" Text='<%# Bind("CoachId") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="ProjectID" >

<ItemTemplate>

<asp:Label ID="lblProjectID" runat="server" Text='<%# Bind("Coach_Last") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Webpath" >

<ItemTemplate>

<asp:Label ID="lblWebpath" runat="server" Text='<%# Bind("Coach_Email") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:conn %>" ID="SqlDataSource1"

runat="server" SelectCommand="SELECT top 5 CoachId, Coach_First, Coach_Last, Coach_Email from tblCoach">

</asp:SqlDataSource>

and in the on click of link button 

protected void lnkPath_OnClick(object sender, EventArgs e)
    {
        GridViewRow datarow = (GridViewRow)(((Control)sender).NamingContainer);
        int i = datarow.RowIndex;
        foreach (GridViewRow rowItem in grdv.Rows)
        {
            if (rowItem.RowIndex == i)
            {                
                string filename = rowItem.Cells[0].ToString();
                if (filename != "")
                {
                    string path = Server.MapPath(filename);
                    System.IO.FileInfo file = new System.IO.FileInfo(path);
                    if (file.Exists)
                    {
                        Response.Clear();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                        Response.AddHeader("Content-Length", file.Length.ToString());
                        Response.ContentType = "application/octet-stream";
                        Response.WriteFile(file.FullName);
                        Response.End();
                    }
                    else
                    {
                        Response.Write("This file does not exist.");
                    }
                }
            }
        }
    }
 Let me know if you have any queries.
Regards,
Ram Reddy Mekha, +91-994-840-4315
http://abhiramreddymekha.blogspot.com

Please Mark as Answer if the post helps you.
0
Ram
4/8/2009 5:04:19 PM

<P mce_keep="true">Yes, that is actually what I do have going for me.&nbsp; Just not sure how to grab the path and download when the hyperlink is clicked.&nbsp; Maybe it would help if I post my connection string.  Which is just about all I've got.  I do have a hyperlink column which, which is displaying my link, but I don't know how to bind it to the webpath column.  thanks
</P>


<form id="Form1" OnInit="PageInit" Runat="server">
      <asp:DataGrid ID="grid" OnLoad="GridLoad" Runat="server" >
<Columns>
    <asp:HyperLinkColumn DataNavigateUrlField="ProjectID" DataTextField="ProjectID" HeaderText="filename"></asp:HyperLinkColumn>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:HyperLink Text="Proj Docs Id" runat="server" >
                    <%# DataBinder.Eval(Container.DataItem, "WebPath" ) %><br />
                </asp:HyperLink>
            </ItemTemplate>
    </asp:TemplateColumn>
</Columns>
</asp:DataGrid>
    </form>

 


C#


public class BasePage : Page
{
    protected DataGrid grid;
    DataView dataView;

    public void PageInit(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection("server=bucklel\\SQLEXPRESS;Initial Catalog=MSIC_Materials_v2;Integrated Security=True");
        string sqlString = "SELECT * FROM ProjectSourceDocs";
        SqlDataAdapter adapter = new SqlDataAdapter(sqlString, con);
        adapter.Fill(ds, "ProjectSourceDocs");
        if (ds.HasErrors) ds.RejectChanges(); else ds.AcceptChanges();
        dataView = ds.Tables["ProjectSourceDocs"].DefaultView;
    }
    public void GridLoad(object sender, EventArgs e)
    {
        grid.HeaderStyle.Font.Bold = true;
        grid.AlternatingItemStyle.BackColor = System.Drawing.Color.LightGray;
        grid.DataSource = dataView;
        grid.DataBind();
    }

 


Call me $wank
0
Swank
4/8/2009 5:09:13 PM

Refer my article

http://www.aspsnippets.com/post/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASPNet.aspx


MAKMark as Answer if this reply helps you
MVP ASP/ASP.Net
MVP ASP/ASP.Net
ASP.Net Hosting : Host DepotMy Site : ASPSnippets
0
mudassarkhan
4/8/2009 5:37:07 PM

Man, Ram Redy & VaserZaid,  You both are amazing. 

Ram Redy I believe the way you gave me is ado correct?  I'm going to use it for now.  And VaserZaid, a lot of logic in yours.  I'm going to work that in when I can.  Again, just can't thank you enought - - and fast too! 

 


Call me $wank
0
Swank
4/8/2009 6:04:06 PM

 All-Star  - - good article I'll take a look at that too!


Call me $wank
0
Swank
4/8/2009 6:05:58 PM

Guys I appreciate your help.  I was able to get some of this code working to fill my datagrid, display a hyperlink and in one case get an error that a file was not found - even though it was.  I fished out something old from one of my co-workers code.  It's into a gridview.  I'm populating just fine and am using a hyperlink field to display my link.  He was using  DataNavigateUrlFormatString  to pass values between pages.  I'm trying to tap the db and pull the virtual path out as when the link is clicked the save/ save as dialog box opens.  I'm hung up on this.  I may have even been given the answer in previous posts but don't know how to integrate it in.  I would certainly appreciate the help to pull a path out.  Could you integrate into my code? thanks much!

 <asp:GridView ID="ctlGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="SampleID"

BackColor="White" BorderColor="#DEDFDE" BorderStyle="groove" BorderWidth="1px"

CellPadding="4" ForeColor="Black" GridLines="Vertical" EmptyDataText="No Records Found">

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

<Columns>

<%--DataNavigateUrlFormatString="~/DownloadingPage.aspx?projID={0}"--%>

<asp:HyperLinkField DataNavigateUrlFields="SampleID" HeaderText="SampleID:" DataTextField="SampleID" DataNavigateUrlFormatString="{0}"/>

<asp:BoundField DataField="Title" HeaderText="Document Title" SortExpression="Title" HtmlEncode="false" />

<asp:BoundField DataField="WebPath" HeaderText="Source Documents" SortExpression="WebPath" HtmlEncode="false" />

</Columns>

</asp:GridView>

 

public partial class LibraryGrid : System.Web.UI.Page

{

SqlConnection myconnection;
protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

this.ctlGridView.DataSource = this.myconnection;

}

myconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["My Database"].ConnectionString);

myconnection.Open();

SqlDataReader myreader = null;

String query = buildQuery(this.TextB_100.Text);  

SqlCommand mycommand = new SqlCommand(query);

mycommand.Connection = myconnection;

myreader = mycommand.ExecuteReader();

ctlGridView.DataSource = myreader;

ctlGridView.DataBind();

grdProject.DataSource = myreader;

grdProject.DataBind();

myconnection.Close();

}

protected static String buildQuery(String SampleID)

{

String query = "SELECT s.SampleID, ssd.Title, ssd.WebPath ";query += "FROM Sample s RIGHT JOIN SampleSourceDocs ssd ON s.SampleID=ssd.SampleID";

if (SampleID.Length > 0) query += " WHERE SampleID LIKE '%" + SampleID + "%'";

return query;

}

}

 


Call me $wank
0
Swank
4/9/2009 10:08:07 PM
Reply:

Similar Artilces:

How do I display a .doc,pdf,xls files in part of a web page
i have webpage. it contains 4 parts. in the 3rd part i need show files in thumbanails type. how can show files like thumbnails type ?. if a user clicks on any one of the file(it may be .doc or .pdf, .xls or any type ) then it need to be opened in 4th part. It means i need show preview of that file same like in my computer. for these two  functionaalities what can i do ? Hey Suresh, I am not clear with what you mean by parts? Is it web parts or a section in the website? Anyway for the thumbnail generation, for an image it works by rescaling the image to a smaller dimension al...

How to File Upload and Download file ( .doc/.pdf/.gif/.exl) from server web browser C#
How to File Upload and Download file ( .doc/.pdf/.gif/.exl) from server web browser Please help me Thanking you Saikat   Uploading: Try a Google search for upload file web server asp.net c#. Download: <a href="http://www.mydomain.com/pathtofile">Download Me</a> HTH,RyanRyan OlshanASPInsider | Microsoft MVP, ASP.NEThttp://ryanolshan.comHow to ask a question HiI want to download this logo.gif . It is possable to download. Download: <a href="http://www.google.com/intl/en/images/logo.gif">Download Me</a> and How to File Upload .doc/.pdf/.gif/.exl file we...

*.txt or *.doc files ? how can i get my record of table1 to *.txt or *.doc files?
hi friends i have table1. and i have username(varchar15) and name(varchar15) and userid(integer) as columname.. and i have 300 records in table1 i want to create *.txt or *.doc files and get my records to *.txt or *.doc files.. i also want to get back my records in *.txt or *.doc to table1 :) how can i do this ? SincerelyMark as me if my question or my answer can be helpful for you :) How would you like to.  My first choice would be a DTS job that exports comma delimited text, but it's easy enough to write this in a lot of different ways. JeffPlease: Don't forget to clic...

how to read a .txt file from .net (web form)
hi, how to read a .txt file line by line and place the contents in a .xls file. ex: if sample.txt file is... Name: abc Company: xyz info ltd. i want abc and xyz info ltd to be cut and saved in .xls file. i already have a .xls template with name and company fields. send solution.......

PDF files and DOC files
Name: Jeff Kopacz Email: Jeffkopacz_at_mchsi.com Product: Firefox Summary: PDF files and DOC files Comments: When using Firefox and have to view a pdf file or Doc file I have to have Adobe Reader or Word started before selecting the file or the computer will lockup. I am using XP and Firefox 1.0.7. If I use either IE or Netscape they will open properly. This has recently occured with either version 6 or 7 Browser Details: Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7 ...

Finishing Touches on Displaying a PDF file in a Web Form
I've successfully built a web app that creates a PDF file on-the-fly and then displays it in a web form.  Here's the core of my code:        // First create the report in PDF format        CrystalDecisions.Shared.DiskFileDestinationOptions destOptions = new CrystalDecisions.Shared.DiskFileDestinationOptions();        string filename = Session["ReportFilename"].ToString();        destOptions.DiskFileName = filename;   ...

How to display a pdf/doc/ppt file in a web browser
I am building an application which need to connect to a db and extract a pdf/doc/ppt file stored in a binary form from it and display it in a web browser.I am facing problem in extracting pdf/doc/ppt files from the db(Ms SQL) and displaying it in the browser. Can any body help me on this.ANGSHUMAN MITRA Hi, Check out this link http://articles.techrepublic.com.com/5100-10878_11-6027591.html on how to control how data is delivered to ASP.NET You might also try searching google for MIME TYPES. Hope this helps, Scott...

how to display pdf, doc or etc files in a portion web browser
I have a task that,in web page i 4 parts or portions. in one part or portions iam able to show files in a directory. if a user clicks any one of the file (it may be any type of file .pdf or .doc or .txt) now i need to open (or showing the preview of this file in other portion of my webpage. how can i  complete this task ? friends please help me.   Put an iframe in your preview section and redirect the url of the iframe to what ever file you want to show there.Hanan Schwartzberg--------------------http://www.lionsden.co.il...

My form can do a file upload but can't do a file download (from a sql image column)
Hi everyone, I've created an ASP.NET C# form that displays a record from a SQL database on the web. I can get everything to load fine except for a file stored in an "image" (datatype) field. What I want is the page to display either a picture or a link or something that the user can click to download the file. I can't seem to figure out is: 1. what type of object to put in the form (text link, image, etc.) to allow for a downloadable file. 2. how to assign the file contained in the image column to some sort of variable. For the other columns in the sql table I...

How to display remote CSV file with my web form's DataGrid?
A remote server has a CSV file that I can browse to as http://the_site.com/path/the_file.csv  (simplified) . I can right-click, save-as a CSV file on my PC. I can then run a Win-form program locally and display the CSV file in a DataGridView control. I used C# 2008 Express with the following code that works fine. The txtFileIn is the path+filename on my PC. 1 {2 OleDbConnection conn = new OleDbConnection(3 "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +4 System.IO.Path.GetDirectoryName(txtFile...

pdf file -> txt file
I want to find a way from PDF file to TXT file (may be use PDF package in perl). Does anyone know how to do that, with an example? thank you very much. Ping 6/20/02 __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com Don't know about perl but my linux distribution comes with the Xpdf package which contains the pdftotext utility. I dare say it will be available for most systems. Ken. -----Original Message----- From: perl is [mailto:isquestion@yahoo.com] Sent: 20 June 2002 2...

upload files and downloading a pdf file
what data type am i going to put to my uploadedFiles column in my database... uploaded files are in document format or .txt  also.. how can i make those files converted into pdf files.. also enable users to download it.. tnx!!! forums.asp.net = "great help"red is the name What kind of database? With SQL Server, its an Image datatype.  If you want ot convert it to a PDF, you need to look at third party add-ons.  There is nothing in the .NET Framework that handles PDFs specifically. Regards Mike [MVP - ASP/ASP.NET]My site varbinary is the datatype you wis...

saving and retrieving various (doc, xls, pdf, etc) files attached to DB row
D7; Sybase ASA 9.0; BDE/ODBC I have a client who wants to attach various document types to rows in the DB. Do I attempt to store them as Blob's or save the document location and open it with its native program? Any suggestions of the best technique, alternate technique or methodology using Delphi 7 or Delphi 2007? Thanks -- Bill Skelton Landmark Data Systems, Inc. Two Old River Place, Suite L Jackson, MS 39202-3435 601-362-0303 Edited by: Bill Skelton on Aug 19, 2008 3:39 PM Bill Skelton schrieb: > D7; Sybase ASA 9.0; BDE/ODBC > > I have a client ...

Convert Gridview Data in to PDf file. or Convert report data in pdf file
 Hi have problem to convert Gridview data into PDF file..let me know is there any solution or open source components..Regards Rambhopal Reddy EPlease remember to click “Mark as Answer” on the post that helps you, and to click “Unmark asAnswer” if a marked post does not actually answer your question. Friend, Check this thread for soultions http://forums.asp.net/t/1164793.aspx and then to http://www.aspnetworld.com/articles/2004011801.aspx   Good luck!     Please Don't forget to click "Mark as Answer" on the post that helped you.This can be benef...

Web resources about - Download a file from sql (doc, txt, xls, pdf) files available in the db to be displayed in a datagrid, gridview, ... - asp.net.web-forms

Hundreds gather for funeral of police shooting victim in Minneapolis
CBS News Hundreds gather for funeral of police shooting victim in Minneapolis Miami Herald Family and friends of Jamar Clark mourned together ...

Obama says U.S. is safe as millions set off on Thanksgiving travel
By Roberta Rampton and Kylie Gumpert WASHINGTON/NEW YORK (Reuters) - President Barack Obama sought to reassure Americans they were safe as millions ...

F-16 Fighter Jet Crashes on Training Mission; Pilot Safe
F-16 fighter jet from Arizona base crashes on New Mexico training mission; pilot safely ejects

Donald Trump To Receive Endorsement From 100 African-American Pastors
Donald Trump is expected to be endorsed for president by 100 African-American pastors and faith-based leaders in a press conference scheduled ...

2011 to 2015 reaches warmest five-year period on record: WMO
Xinhua 2011 to 2015 reaches warmest five-year period on record: WMO Xinhua Michel Jarraud, Secretary-General of World Meteorological Organization ...

Watch: Eagles of Death Metal Give First Interview Since Paris Attacks
Two weeks after ISIS militants besieged the Nov. 13 concert of rock band Eagles of Death Metal, the group has opened up for the first time about ...

No Thanksgiving parade for the Estefans _ they're too busy
NEW YORK (AP) — Songs from the new musical celebrating the lives of Gloria and Emilio Estefan will have the honor of kicking off the Macy's Thanksgiving ...

Exclusive: U.S. has urged legal reforms abroad to block Islamic State recruits
By Mark Hosenball WASHINGTON (Reuters) - The U.S. Justice Department has provided specific suggestions to governments in Europe and elsewhere ...

George Osborne ducks big welfare cuts and INCREASES spending
Despite weeks of warnings of savage cuts, the Chancellor ditched plans to slash the £30billion tax credits bill. He will now even breach his ...

Multiple Members of the U.S. Military Suspended Over Airstrike on Doctors Without Borders Hospital in ...
Several soldiers and airman have been removed from duty, the Associated Press reports , after making preventable errors and violating U.S. rules ...

Resources last updated: 11/26/2015 4:22:29 AM