Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

how to insert images into database and how to retrieve and bind images to gridview using asp.net (or) save and retrieve images from database using asp.net

Jan 2, 2011
Introduction

Here I will explain how insert and retrieve images from database and how to bind images to gridview using asp.net.

Description:

I have worked on one social networking site at that time we save all the images in to directory folder and we save image path into database at that time I got idea to implement concept like inserting images into database and retrieving the images from database and binding images to gridview using asp.net for that we need follow below steps

First Design table like this in your SQL Server database and give name as Image

Column Name
Data Type
Allow Nulls
ImageId
Int(set identity property=true)
No
ImageName
Varchar(50)
Yes
Image
image
Yes
After that Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Inserting images into databse and displaying images with gridview</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:500px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Image Name:
</td>
<td>
<asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
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>
</div>
<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
After that add using System.IO; using System.Data.SqlClient; and using System.Configuration; namespaces and write the following code in code behind



string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
/// <summary>
/// btnUpload_Click event is used to upload images into database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting 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;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (@imagename,@imagedata)", connection);
cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
/// <summary>
/// function is used to bind gridview
/// </summary>
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}
Here we need to restrict user to upload only image formats in file upload control for that validaiton check this post how to validate file type in file upload control using javascript

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 

string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}

Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>

Demo

Download sample code attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

224 comments :

«Oldest   ‹Older   201 – 224 of 224   Newer›   Newest»
VtBear said...

Is this possible/available in VB?

Unknown said...

sir i found error ,, plz guide me how to remove this ........

Exception Details: System.InvalidOperationException: Instance failure

Line 61: daimages.Fill(dt);

java2novice said...

nice. for java example, visit http://java2novice.com site

Bvenkat Jeewesh said...

nice post;-)

Bvenkat Jeewesh said...

nice post.

Anonymous said...

i am not getting the images plz help

Unknown said...

I am not getting the images in gridview even though i kept ashx code....................
can any one give me the solutions
thank u

Pooja Pate said...

hiii sir
plz send me a medical bill form in multiple medicine..
patelsachin30@gmail.com
09753533046

Unknown said...

hi suresh sir..
i should save the image through handler like the following path..
".//productimage//id"...that id should vary dynamically...for eg,2.jpg should be saved in ".//productimage//23"...then 4.jpg should be saved in ".//productimage//24"....that id is nothing but table's last inserted row id..productimage is the main folder...23,24 are sub folders....canu pls help me

sunil said...

hi
sir

Anonymous said...

Hi sir your blog is a great help for me, i have doubt, that i have a dropdown list values come from sqlserver column, and based on this selection in dropdown value, the popup grid will be displayed. i tried a lot but can't able to fire a different gridview . Can U Pls Help Me to Solve this Problem.

Anonymous said...

I use this code to display image, but it only display ".jpg" images. Other images i have uploaded in DB but its not showing. Need your help, Thanx in advance.

string imageid = imgid;
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from WhyUs_Mst where Id=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();

Mahesh said...

Hi Suresh,

How can i save the images concatenation with Id In to folder

Unknown said...

When i try to insert image into database, i tried this method. But on this particular line
byte[] imgbyte = new byte[length]; (It shows error like String or Binary Data truncated!!
How to solve this??so it also show error in
Insert statement:
if (FileUpload1.HasFile)
{
//getting length of uploaded file
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 imagename = TextBox1.Text;
string status = "active";
string date=DateTime.Today.ToShortDateString();
string cmdstr = "insert into mapplied(imagename,pic,category,name,gender,company,designation,bdate,referred,oemail,omobile,oaddress,ophone,pemail,pmobile,paddress,pphone,status,dmembership)values('"+imagename+"','"+imgbyte+"','"+DropDownList2.SelectedItem.ToString()+"','"+TextBox13.Text+"','"+RadioButtonList1.SelectedItem.ToString()+"','"+TextBox14.Text+"','"+TextBox15.Text+"','"+TextBox17.Text+"','"+TextBox16.Text+"','"+TextBox18.Text+"','"+TextBox20.Text+"','"+TextBox22.Text+"','"+TextBox21.Text+"','"+TextBox23.Text+"','"+TextBox24.Text+"','"+TextBox26.Text+"','"+TextBox25.Text+"','"+status+"','"+date+"')";
SqlConnection con=new SqlConnection(constr);
con.Open();
SqlCommand cmd=new SqlCommand(cmdstr,con);
cmd.ExecuteNonQuery();


}


Unknown said...

Hiii Suesh
This codes is perfectly work on local but when m upload on server the same code its give a error give me a suggestion if you have
Error is : Server Error in '/' Application.
Access to the path 'G:\PleskVhosts\friendsanddevelopers.in\Nitin\1 (7).jpg' is denied.

Please help me

Anonymous said...

this article worked perfectly fine ,gr8
thanks.

Anonymous said...

Please Write nit and clean code. your concept is good but code is unreadable.

Unknown said...

Hi Sir,

I have tried so many times but not getting image showing green symbol.
is we have to save the image at server also.totally confused if we are saving at server then when the user increases then the application will be having load.please reply thanks in advance.

Unknown said...

Hello, I am getting an error in the ashx file on line 10 saying that the NullReferenceException was unhandled by user code. It mentions that i can either try to allow nulls for the image id column or i can create a "new" keyword to create an object instance. Any help?

Praveenkumar said...

thanks

Unknown said...

Thank you Mr.Suresh

Unknown said...

Dear suresh
I'm using query string send id one page to another page. Now I want to bind image from data base behalf of ID..
can you tell me how to?

Anonymous said...

Hi Suresh, I have been reading your articles from many days, I have some question can you answer it. Actually I have a database in mysql storing image data in blob format using jsp but it too heavy for browser to browse, it take much time than expectation. Do you have any idea what to do... Thanks in advance....

Khasiat Walatra G-Sea said...

nice

«Oldest ‹Older   201 – 224 of 224   Newer› Newest»

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.