How to save images in database and display it in gridview control using HTTP Handler in asp.net

By
Introduction :-
This articles helps to insert the image in database and display it in Gridview control with the help of Generic Handler.ashx class in asp.net. This is very important concepts to display the images in Gridview control.In our previous post, you can  show the images in Gridview control  with help of other different ways.But both technique are different and unique. You can download whole application from below and run it on your visual studio without facing any problems.
Description:-
    I have performed many things to build this useful application in asp.net as given below;-
  • First create a page(home.aspx) and drag and drop some controls on page such as Label,TextBox,FileUpload , Button and SqlDataSource.
  • After that Add SQL database Database.mdf and create a student table with some column such as sid,name,email,image.
  • After that create second page (show_data.aspx) , drag and drop Gridview control on it and Bind table columns data with gridview.
  • After that Add Generic Handler class (Handler.ashx).
  • You can upload image size less than equal to (<=) 50 KB,otherwise this application will show an error message on the page.
What is Handler ?
The HTTP Handler is a class that allows us to process a request and send a response to the web browser (e.g. Google chrome,Firefox,Internet Explorer,opera etc.).It can handle only one request at a time. This class is helpful to show the image in Gridview from the database.
There are some steps to make this application in asp.net as given below:-
Step  1 : - First open your visual studio --> File -->New--> website -->Select ASP.NET Empty Website -->OK -->Open Solution Explorer -->Add a New web form (home.aspx)--> Drag and drop  Label,TextBox,FileUpload , Button and SqlDataSource controls on the page from the toolbox as shown below:-


form

Step  2 : -  Now open Solution Explorer --> Add a Sql Database (Database.mdf) --> and create a student table with some columns as shown below:-


mdf file

Note:- 
Set Identity Specification (Is Identity) = yes in sid column
If you facing problem to add Database.mdf file inside your project then follow below links
Step  3 :- Now Add a New web form (show_data.aspx) in your project --> drag and drop Gridview control on page from the toolbox .
Step  4 :- Now write the c# codes on Upload and Save Button & Show Gridview Data button clicks (home.aspx..cs)as given below:-

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Data;

public partial class home : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);   
    protected void Button1_Click(object sender, EventArgs e)
    {
        con.Open();
        try
        {
            byte[] image_Byte = new byte[FileUpload1.PostedFile.InputStream.Length + 1];
            FileUpload1.PostedFile.InputStream.Read(image_Byte, 0, image_Byte.Length);
            //Check whether image size 51200 byte or 50 kb  
            long size_img = FileUpload1.PostedFile.InputStream.Length;
            if (size_img <= 51200)
            {
                SqlCommand cmd = new SqlCommand("insert into student values(@name,@email,@img)", con);
                cmd.Parameters.AddWithValue("name", TextBox1.Text);
                cmd.Parameters.AddWithValue("email", TextBox2.Text);
                cmd.Parameters.AddWithValue("img", image_Byte);
                cmd.ExecuteNonQuery();
                Label1.Text = "Data inserted in database successfully ";
            }
            else
            {
                Label1.Text = "Enter image size less than 50 kb";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
        finally
        {
            con.Close();
        }
    } 
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("show_data.aspx");
    }
}

Note:-
  • This code helps to insert the image in sql database as well as show the images in gridview control with the help of HTTP Handler class.
  • Here i have used exception handling concepts also.
  • I have already added all Namespaces ,you can see it in above codes. 
Step  5 :-  Now Open Solution Explorer --> Add Generic Handler (Handler.ashx) class in Project --> Write the following c# codes as given below:-

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Data;

public class Handler : IHttpHandler {
    SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);   
    public void ProcessRequest (HttpContext context) 
    {
        string image_id =context.Request.QueryString["imgid"];
        con2.Open();
        SqlCommand cmd = new SqlCommand("select image from student where sid="+image_id ,con2);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((byte[])dr["image"]);
        con2.Close();
        
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

Note : -
  • I have already added all Namespaces in above codes.You can see it and remember it.
Step  6 : - Now Open home.aspx page --> Configure SqlDataSource  Setting's --> select Database.mdf and set connection  string= "myConnectionString' --> and proceed with Next Button as shown below:-


connections

Step  7 : -  Now open Show_Data.aspx page --> Click Source --> Bind the Grirdview data as well as HTTP Handeler URL as shown below:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="show_data.aspx.cs" Inherits="show_data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
         <Columns>
         <asp:BoundField ItemStyle-Width= "150px" HeaderText = "Sid" DataField="sid" />
        <asp:BoundField ItemStyle-Width= "150px" HeaderText = "Name" DataField="name" />
        <asp:BoundField  ItemStyle-Width= "150px" HeaderText = "Email" DataField="email" />
       <asp:TemplateField HeaderText="Image">
       <ItemTemplate>
       <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?imgid="+ Eval("sid") %>' Height="150px" Width="150px"/>
      </ItemTemplate>
      </asp:TemplateField>
      </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Step  8 : - Now Run the application(press F5) --> Enter required field details and press Upload and Save Button --> You will see following output as show below:-


output

Step  9 : - Now Press Show Gridview Data Button--> you will see following output as shown below:-
output page

Step  10 : - You you upload image size greater than 50 KB then you will get an error message on the screen as shown below:-
error page

Step  11 : - Now Open Database.mdf file from Solution Explorer window --> You will see ,data inserted in student table as shown below:-


output

For More...
  1. How to use Navigation controls in asp.net website
  2. How to use webform controls on asp.net website easily
  3. File handling Real time application in windows form application
  4. Delegate concepts in c#
  5. Call by value and call by reference in c#
  6. Structure and class concepts in c#
  7. Properties concepts in c#
  8. How to create DLL file and use it in .NET applications
  9. How to add captcha image in asp.net application
  10. Opps concepts in c#
Download Whole Attached file
  Download

0 comments:

Post a Comment

Powered by Blogger.