Friday 21 December 2012

Image code with sql server


Image Insert /Retrieve  with  sql server Database Table
Asp.net code insert image by  code
cmd.Parameters.Add("@ProductPicture", SqlDbType.VarBinary).Value = uploadProduct.FileBytes;

retrieve image from sql server databse
we take new asp.net page and convert byte to response. BinaryWrite

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetProductPicture.aspx?ProductID=" + Eval("ProductID")%>' alt="Image" Width="150px" Height="100px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1" style="border-radius:5px;" />

Now productPicture page code
protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = null;
        try
        {
           int Prod_Id = Convert.ToInt32(Request.QueryString["ProductID"].ToString());
          con = new SqlConnection(ConfigurationManager.AppSettings["AsCon"].ToString());
            if (con != null)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand("select ProductPicture from ProductMaster where ProductID=" + Prod_Id + "", con);
            byte[] product = (byte[])cmd.ExecuteScalar();
            Response.BinaryWrite(product);
        }
        catch (Exception ex)
        {
           // Mailer.SendTechnicalMail(ex.Message);
        }
        finally
        {
            if (con != null)
            {
                con.Close();
            }
        }
    }

No comments:

Post a Comment