Retreive PDF file stored om SQL Server Database and then display on page

Last Reply on Sep 23, 2012 08:09 AM By Mudassar

Posted on Sep 23, 2012 03:07 AM

in gridview i have two link button that is  "VIEW"  and "DOWNLOAD"  if i click "view" that pdf file wll display in an other page if i click download that file will be downloaded.. 

how can i do this.. is thereany simple way  ... 

Posted on Sep 23, 2012 08:09 AM

With reference to this article

Save and Retrieve Files from SQL Server Database using ASP.Net

Create a page called as DisplayFile.aspx and pass the Id of the file as querystring

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int id = int.Parse(Request.QueryString["id"]);
            Display(id);
        }
    }

    private void Display(int id)
    {
        DataSet ds = GetData("select * from tblFiles where Id=@Id", id);
        Byte[] bytes = (Byte[])ds.Tables[0].Rows[0]["Data"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }

    private DataSet GetData(string query, int id)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr_files"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                cmd.Parameters.Add("@Id", id);
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds;
                }
            }
        }
    }