Store and View PDF Files in a GridView

This article explains how to store and view PDF files in a GridView in ASP.NET.

Look at the following procedure.

Step 1: Database Structure.

Query

Create a table named tbl_pdf.

table design

WebConfig

WebConfig

Upload.aspx Code

  1. <asp:FileUpload ID="”FileUpload”" runat=”server” /> <asp:Button ID="”btnsubmit”" runat=”server” Text=”Upload”  />  
  2. <asp:Button ID="”btncancel”" runat=”server” Text=”Cancel” /> <asp:Label ID="”alert”" runat=”server”></asp:Label>  
  3. <asp:GridView ID="”GridView1″" runat=”server” /> <asp:Label ID="”Label1″" runat=”server”></asp:Label>  
Screen

file upload

Upload.aspx.cs

Step 2: Storing PDF files into database.

Source Code
  1. protected void btnsubmit_Click(object sender, EventArgs e)  
  2. {  
  3.    try  
  4.    {  
  5.       byte[] pdf = null;  
  6.       if(FileUpload.HasFile & FileUpload.PostedFile != null)  
  7.       {  
  8.          HttpPostedFile file = FileUpload.PostedFile;  
  9.          pdf = new byte[file.ContentLength];  
  10.          file.InputStream.Read(pdf, 0, file.ContentLength);  
  11.       }  
  12.       SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[“userconnstring”].ConnectionString);  
  13.       SqlCommand cmd = new SqlCommand(“insert into tbl_pdf ([Document],[DocumentName]) values (@Document,@DocumentName)”, con);  
  14. con.Open();  
  15.       cmd.Parameters.AddWithValue(“@DocumentName”, FileUpload.PostedFile.FileName);  
  16.       cmd.Parameters.AddWithValue(“@Document”, pdf);  
  17.       cmd.ExecuteNonQuery();  
  18.       alert.Text = “Document Uploaded Successfully”;  
  19.       con.Close();  
  20.    }  
  21.    catch(Exception ex)  
  22.    {  
  23.       throw ex;  
  24.    }  
  25. }  
Gridview.aspx
  1. <asp:GridView ID=”GridView1″ runat=”server” />  
Step 3: Bind data into the GridView using a simple datasource connection.

Screen

datasource connection

After binding a GridView looks like this.
  1. <asp:GridView ID="”GridView1″" runat=”server” AutoGenerateColumns=”False” DataSourceID=”PDFViewer” EnableModelValidation=”True”>  
  2. <Columns>  
  3. <asp:BoundField DataField=”Doc_ID” HeaderText=”ID” SortExpression=”Doc_ID” />  
  4. <asp:BoundField DataField=”DocumentName” HeaderText=”DocumentName” SortExpression=”DocumentName” />  
  5. <asp:TemplateField ItemStyle-HorizontalAlign=”Center” >  
  6. <ItemTemplate>  
  7. <asp:LinkButton ID="”lnkView”" runat=”server” Text=”View” OnClick=”View” CommandArgument='<%# Eval(“Doc_ID”) %>’></asp:LinkButton>  
  8. </ItemTemplate>  
  9. </asp:TemplateField>  
  10. </Columns>  
  11. </asp:GridView>  
  12. <asp:SqlDataSource ID="”PDFViewer”" runat=”server” ConnectionString=”<%$ ConnectionStrings:WordpressConnectionString %>” SelectCommand=”SELECT [Doc_ID],[DocumentName] FROM [tbl_pdf]”></asp:SqlDataSource>  
Step 4: Now create a Generic Handler to view PDF in a GridView and create a new handler in ASP.Net as in the following:

Generic Handler

Pdfhandler.ashx.cs Code:[Full] 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. namespace MyApplication  
  9. {  
  10.    /// <summary>  
  11.    /// Summary description for ImageViewer  
  12.    /// </summary>  
  13.    public class ImageViewer : IHttpHandler  
  14.    {  
  15.       public void ProcessRequest(HttpContext context)  
  16.       {  
  17.          Int32 theID;  
  18.          if (context.Request.QueryString[“id”] != null)  
  19.          theID = Convert.ToInt32(context.Request.QueryString[“id”]);  
  20.          else  
  21.          throw new ArgumentException(“No parameter specified”);  
  22.          context.Response.ContentType = “Application/pdf”;  
  23.          Stream strm = DisplayImage(theID);  
  24.          byte[] buffer = new byte[2048];  
  25.          int byteSeq = strm.Read(buffer, 0, 2048);  
  26.          while (byteSeq > 0)  
  27.          {  
  28.             context.Response.OutputStream.Write(buffer, 0, byteSeq);  
  29.             byteSeq = strm.Read(buffer, 0, 2048);  
  30.          }  
  31.       }  
  32.       public Stream DisplayImage(int theID)  
  33.       {  
  34.          string str = “Data Source=.;Initial Catalog=Wordpress;Integrated Security=True”;  
  35.          SqlConnection connection = new SqlConnection(str);  
  36.          string sql = “SELECT Document FROM tbl_pdf WHERE Doc_ID = @Doc_ID”;  
  37.          SqlCommand cmd = new SqlCommand(sql, connection);  
  38.          cmd.CommandType = CommandType.Text;  
  39.          cmd.Parameters.AddWithValue(“@Doc_ID”, theID);  
  40.          connection.Open();  
  41.          object theImg = cmd.ExecuteScalar();  
  42.          try  
  43.          {  
  44.             return new MemoryStream((byte[])theImg);  
  45.          }  
  46.          catch  
  47.          {  
  48.             return null;  
  49.          }  
  50.          finally  
  51.          {  
  52.             connection.Close();  
  53.          }  
  54.       }  
  55.       public bool IsReusable  
  56.       {  
  57.          get  
  58.          {  
  59.             return false;  
  60.          }  
  61.       }  
  62.    }  
  63. }  
Step 5: In the next step add a linkbutton in GridView to view the PDF Files from the database:
  1. <asp:TemplateField ItemStyle-HorizontalAlign=”Center” > <ItemTemplate> <asp:LinkButton ID=”lnkView” runat=”server” Text=”View” OnClick=”View” CommandArgument='<%# Eval(“Doc_ID”) %>’></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>  
Step 6: Create a OnClick view function behind the upload.aspx.cs and call the Generic handler here.

Code 
  1. protected void View(object sender, EventArgs e)  
  2. {  
  3.    int id = int.Parse((sender as LinkButton).CommandArgument);  
  4.    string embed = “”;  
  5.    embed += “If you are unable to view file, you can download from here“;  
  6.    embed += ” or download Adobe PDF Reader to view the file.”;  
  7.    embed += “”;  
  8.    Label1.Text = string.Format(embed, ResolveUrl(“~/Pdfhandler.ashx?Id=”), id);  
  9. }  
Output

output