Thursday, 10 April 2014

How to inserting images into database and retrieving the images from database and binding images to gridview and how to show large image preview when hover on GridView image using asp.net

In this article I will explain how to inserting images into database and retrieving the images from database and binding images to gridview and how to show large image preview when hover on GridView image using asp.net and JQuery
Or
How to save images into DB and retrieve images from Database using Image Handler.ashx and how to show large image preview when hover on GridView image using asp.net and JQuery

Or
How to save and retrieve images from Database using ASP.NET and how to show large image preview when hover on GridView image using asp.net and JQuery


In this scenario inserting images into database and retrieving the images from database and binding images to GridView using asp.net and how to show large image preview when hover on GridView image using asp.net

Output:



Sample GridView onmouseover code in Jquery.

<script type="text/javascript" language="javascript">
$(document).ready(function () {
ShowImagePreview();
});
// Configuration of the x and y offsets
function ShowImagePreview() {
xOffset = 100;
yOffset = 40;

$("a.preview").hover(function (e) {
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
$("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
$("#preview")
.css("top", (e.pageY - xOffset) + "px")
.css("left", (e.pageX + yOffset) + "px")
.fadeIn("slow");
},

function () {
this.title = this.t;
$("#preview").remove();
});

$("a.preview").mousemove(function (e) {
$("#preview")
.css("top", (e.pageY - xOffset) + "px")
.css("left", (e.pageX + yOffset) + "px");
});
};
</script>


I have created one table in Database.

1.      tblImages



First we need to establish a connection in Web.config file.

<connectionStrings>
<add name="connectionString" connectionString="Data Source=LocalHost;uid=sa1;password=Con@123;Initial Catalog=practice"/>
</connectionStrings>

Below is the page design.



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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Save images into databse and displaying images with gridview</title>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
ShowImagePreview();
});
// Configuration of the x and y offsets
function ShowImagePreview() {
xOffset = 100;
yOffset = 40;

$("a.preview").hover(function (e) {
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
$("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
$("#preview")
.css("top", (e.pageY - xOffset) + "px")
.css("left", (e.pageX + yOffset) + "px")
.fadeIn("slow");
},

function () {
this.title = this.t;
$("#preview").remove();
});

$("a.preview").mousemove(function (e) {
$("#preview")
.css("top", (e.pageY - xOffset) + "px")
.css("left", (e.pageX + yOffset) + "px");
});
};

</script>
<style type="text/css">
#preview {
position: absolute;
border: 3px solid #ccc;
background: #333;
padding: 5px;
display: none;
color: #fff;
box-shadow: 4px 4px 3px rgba(103, 115, 130, 1);
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td align="center" colspan="2">
<b style="color: maroon; font-size: large;">Registration Form Save User Images</b>
</td>
</tr>
<tr>
<td align="right">FirstName
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">LastName
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">Email
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">Phone No
</td>
<td>
<asp:TextBox ID="txtphone" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">City
</td>
<td align="left">
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">Image Name:
</td>
<td>
<asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">Upload Image:
</td>
<td>
<asp:FileUpload ID="fileuploadImage" runat="server" />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center">
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="maroon" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText="First Name" DataField="Firstname" />
<asp:BoundField HeaderText="Last Name" DataField="Lastname" />
<asp:BoundField HeaderText="Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" class="preview" ToolTip='<%#Bind("imagename") %>' NavigateUrl='<%# "ImageHandler.ashx?ImID="+ Eval("UserID") %>' runat="server">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("UserID") %>' Height="100px" Width="100px" />
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Below is the total code for saving and retrieving data from Database.

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

public partial class SaveImagesToDb : System.Web.UI.Page
{
SqlConnection conImage = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
//Bind data to GridView
private void BindGridData()
{
SqlCommand command = new SqlCommand("SELECT UserID,FirstName,LastName,imagename,image from tblImages", conImage);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dtBindGridData = new DataTable();
daimages.Fill(dtBindGridData);
gvImages.DataSource = dtBindGridData;
gvImages.DataBind();
}
// Save user information with image
protected void btnUpload_Click(object sender, EventArgs e)
{
//Check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//Length of uploaded file
int length = fileuploadImage.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 = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
conImage.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO tblImages (FirstName,LastName,Email,PhoneNo,City,imagename,image) VALUES ('" + txtfname.Text + "','" + txtlname.Text + "','" + txtEmail.Text + "','" + txtphone.Text + "','" + txtCity.Text + "','" + txtImageName.Text + "',@imagedata)", conImage);
cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
conImage.Close();
if (count == 1)
{
BindGridData();
txtfname.Text = string.Empty;
txtlname.Text = string.Empty;
txtEmail.Text = string.Empty;
txtphone.Text = string.Empty;
txtCity.Text = string.Empty;
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully !')", true);
}
}
}
}
After Completion of above code we need to add Handler file to our Website to retrieve images from database. We save our images in binary format getting the binary format of data from database.

Handler is a simple class that allows you to process a request and return a response to the browser. It can handle only one request at a time, which in turn gives high performance.

Right Click on your Website add new Handler.ashx file and give name as ImageHandler.ashx and write the following code in page request method like this

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

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;

public class ImageHandler : IHttpHandler
{
SqlConnection conImage = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
conImage.Open();
SqlCommand command = new SqlCommand("select image from tblImages where UserID=" + imageid, conImage);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
conImage.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}


No comments:

Post a Comment