Wednesday 4 April 2012

insert and retrieve images from database and how to bind images to gridview using asp.net.


Introduction:
In this article I will explain how to insert images into database and display images from database into gridview.
Column Name
Data Type
ProductId
Int(set identity property=true)
Productname
varchar(50)
ProductAmount
bigint)
ProductImage
image
 
Now Design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
        <asp:Label ID="Label1" runat="server" Text="ProductName"></asp:Label>
        <asp:TextBox ID="txtProductname" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="ProductAmount"></asp:Label>
        <asp:TextBox ID="txtproductamount" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label3" runat="server" Text="ProductImage"></asp:Label>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:Button ID="Button1" runat="server" Text="UPLOAD" onclick="Button1_Click" />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
            CellPadding="2" ForeColor="Black" GridLines="None">
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
        <Columns>
        <asp:BoundField HeaderText ="Productname" DataField ="Productname" />
        <asp:BoundField HeaderText ="ProductAmount" DataField ="ProductAmount" />
        <asp:TemplateField HeaderText ="Productimage">
        <ItemTemplate >
        <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?ProductId="+ Eval("ProductId") %>' Height="50px" Width="50px"/>
            <asp:Panel ID="Panel1" runat="server" Width ="200" Height ="200">
           <asp:Image ID="Image" runat="server" ImageUrl='<%# "Handler.ashx?ProductId="+ Eval("ProductId") %> '/>
            </asp:Panel>
        <asp:HoverMenuExtender ID="HoverMenuExtender1" runat="server" PopupControlID="Panel1" TargetControlID="Image1" PopupPosition="Right">
            </asp:HoverMenuExtender>
        </ItemTemplate>
        </asp:TemplateField>
                </Columns>
            <FooterStyle BackColor="Tan" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
                HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <SortedAscendingCellStyle BackColor="#FAFAE7" />
            <SortedAscendingHeaderStyle BackColor="#DAC09E" />
            <SortedDescendingCellStyle BackColor="#E1DB9C" />
            <SortedDescendingHeaderStyle BackColor="#C2A47B" />
        </asp:GridView>
        </div>
    </form>
</body>
</html>

After completion of aspx page design add using System.IO; reference in codebehind and write the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class ProductImage : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=SHAILAJA;Initial Catalog=peers;User ID=sa;Password=123");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            int length = FileUpload1.PostedFile.ContentLength;
            //        //create a byte array to store the binary image data
            byte[] imgbyte = new byte[length];
            //            //store the currently selected file in memeory
            HttpPostedFile img = FileUpload1.PostedFile;
            //            //set the binary data
            img.InputStream.Read(imgbyte, 0, length);
            string Productname = txtProductname.Text;
            string ProductAmount = txtproductamount.Text;
            con.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO Productimage (Productname,ProductAmount,ProductImage) VALUES (@Productname,@ProductAmount,@ProductImage)", con);
            cmd.Parameters.Add("@Productname", SqlDbType.VarChar, 50).Value = Productname;
            cmd.Parameters.Add("@ProductAmount", SqlDbType.VarChar, 50).Value = ProductAmount;
            cmd.Parameters.Add("@ProductImage", SqlDbType.Image).Value = imgbyte;
            int count = cmd.ExecuteNonQuery();
            con.Close();
            if (count > 0)
            {
                BindGridData();
                txtProductname.Text = string.Empty;
                txtproductamount.Text = string.Empty;

                string msg = "<script>alert('inserted sucessfully')</script>";
                ScriptManager.RegisterStartupScript(this, typeof(Control), "alertmsg", msg, false);
            }

        }
    }
    private void BindGridData()
    {
        SqlDataAdapter sda = new SqlDataAdapter("select * from Productimage", con);
        DataSet ds = new DataSet();
        sda.Fill(ds);
       GridView1.DataSource = ds;
       GridView1.DataBind();
    }
}


After Completion of above code we need to add HTTPHandler file to our project to retrieve images from database because we save our images in binary format getting the binary format of data from database it’s easy but displaying is very difficult that’s why we will use HTTPHandler to solve this problem.

Here HTTPHandler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance.

Right Click on your project add new HTTPHandler.ashx file and give name as ImageHandler.ashx and write the following code in pagerequest method like this 

<%@ WebHandler Language="C#" Class="Handler" %>
using System.Data.SqlClient;
using System.Data;
public class Handler : IHttpHandler
{
        public void ProcessRequest (HttpContext context)
    {
        string Productid = context.Request.QueryString["ProductId"];
        SqlConnection con = new SqlConnection("Data Source=SHAILAJA;Initial Catalog=peers;User ID=sa;Password=123");
        con.Open();
        SqlCommand cmd = new SqlCommand("select ProductImage from Productimage where ProductId=" + Productid, con);
        SqlDataReader dr=cmd.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        con.Close();
        context.Response.End();
    }
     public bool IsReusable {
        get {
            return false;
        }  }}
Demo:


No comments:

Post a Comment