Friday 4 April 2014

How to inserting images into database and retrieving the images from database and binding images to gridview using asp.net Or How to save images into DB and retrieve images from Database using Image Handler.ashx Or


In this article I will explain how to inserting images into database and retrieving the images from database and binding images to gridview using asp.net

Or

How to save images into DB and retrieve images from Database using Image Handler.ashx

Or

How to save and retrieve images from Database using ASP.NET


In this scenario inserting images into database and retrieving the images from database and binding images to gridview using asp.net

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.



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Save images into databse and displaying images with gridview</title>
</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:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("UserID") %>' Height="100px" Width="100px" />
</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();
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;
}
}
}

Output:

Step 1: First record inserted into Database


Step 2: Second record inserted into Database





No comments:

Post a Comment