To insert an image into the database and display it on the gridview


This code deals with inserting an image into the database and displaying it on the gridview

DataBase-Table



This is the structure of the table

Parameter Name Datatype

PersonID int
PersonEmail varChar(max)
Sex char(10)
DOB DateTime
PersonImage Image
PersonImageType varchar(255)

Stored Procedure



The Stored Procedure for the above table is as follows


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER procedure [dbo].[sp_imguploadSH]
(
@PersonID int,
@PersonEmail varchar(max),
@Sex char(10),
@DOB datetime,
@PersonImage Image,
@PersonImageType varchar(255)
as
begin
insert into person(PersonEmail,Sex,DOB,PersonImage,personImageType) values(@PersonEmail,@Sex,@DOB,@PersonImage,@PersonImageType)


To Insert an image



To insert an image into the database

* In the code-behind, add the namespace System.IO,using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;

* In The ButtonClick Event do the following


protected void btnSubmit_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
SqlConnection con = new SqlConnection(connection);
SqlCommand storepersonDetail = new SqlCommand("Insert into Person " + "(PersonEmail, Sex, DOB,PersonImage,personImageType) " + " values (@PersonEmail,@Sex,@DOB,@PersonImage,@PersonImageType)", con);
storepersonDetail.Parameters.Add("@PersonEmail", SqlDbType.VarChar, 255).Value = TextBox3.Text;
storepersonDetail.Parameters.Add("@Sex", SqlDbType.VarChar, 10).Value = TextBox2.Text;
storepersonDetail.Parameters.Add("@DOB", SqlDbType.DateTime).Value = Convert.ToDateTime(TextBox4.Text);
storepersonDetail.Parameters.Add("@PersonImage", SqlDbType.Image, myimage.Length).Value = myimage;
storepersonDetail.Parameters.Add("@PersonImageType", SqlDbType.VarChar, 255).Value = FileUpload1.PostedFile.ContentType;


con.Open();
storepersonDetail.ExecuteNonQuery();
con.Close();
}
}


The Above will be help you to save the image into the database
To display an image

* Go for GenericHandler

Display an image with generic Handler



Handler
: Handler is nothing but a class that allows to process a request and return a response to the browser

* Here The handler class is thus used to perform Image Retrieval


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

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


public class Handler : IHttpHandler {

string Connection = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;

public void ProcessRequest (HttpContext context) {
SqlConnection con = new SqlConnection(Connection);
con.Open();
string sql = "Select PersonImage, PersonImageType from Person where PersonID=@PersonID";
SqlCommand cmd = new SqlCommand(sql, con);
SqlParameter PersonID = new SqlParameter("@PersonID", SqlDbType.Int, 0);
PersonID.Value = context.Request.QueryString["id"]; cmd.Parameters.Add(PersonID);
cmd.Prepare(); SqlDataReader dr = cmd.ExecuteReader(); dr.Read();
context.Response.ContentType = dr["PersonImageType"].ToString();
context.Response.BinaryWrite((byte[])dr["PersonImage"]);
dr.Close();
con.Close();


}

public bool IsReusable {
get {
return false;
}
}
}


To BindData



we can bind the GridView control to display all the records in the table as follows

 
GridView1.DataSource = FetchAllImagesInfo();
GridView1.DataBind();




public DataTable FetchAllImagesInfo()
{
SqlConnection con = new SqlConnection(connection);
string sql = "Select * from person";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}


Full Code




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

public partial class Default2 : System.Web.UI.Page
{
string connection = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
SqlDataAdapter DA;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
SqlConnection con = new SqlConnection(connection);
SqlCommand storepersonDetail = new SqlCommand("Insert into Person " + "(PersonEmail, Sex, DOB,PersonImage,personImageType) " + " values (@PersonEmail,@Sex,@DOB,@PersonImage,@PersonImageType)", con);
storepersonDetail.Parameters.Add("@PersonEmail", SqlDbType.VarChar, 255).Value = TextBox3.Text;
storepersonDetail.Parameters.Add("@Sex", SqlDbType.VarChar, 10).Value = TextBox2.Text;
storepersonDetail.Parameters.Add("@DOB", SqlDbType.DateTime).Value = Convert.ToDateTime(TextBox4.Text);
storepersonDetail.Parameters.Add("@PersonImage", SqlDbType.Image, myimage.Length).Value = myimage;
storepersonDetail.Parameters.Add("@PersonImageType", SqlDbType.VarChar, 255).Value = FileUpload1.PostedFile.ContentType;


con.Open();
storepersonDetail.ExecuteNonQuery();
con.Close();

GridView2.DataSource = FetchAllImagesInfo();
GridView2.DataBind();
GridView2.Visible = true;





}
}
public DataTable FetchAllImagesInfo()
{
SqlConnection con = new SqlConnection(connection);
string sql = "Select * from person";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

}


Make sure to bind the image in the grid as follows

<asp:TemplateField >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?id=" + Eval("Img_Id") %>' />
</ItemTemplate>
</asp:TemplateField>


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: