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   1 – 200 of 224   Newer›   Newest»
zia said...

Good but i prefer storing images in filesystem cuz my webhost provides limited database space

Suresh Dasari said...

hi zia thanks for you suggestion i have written article to save images in filesystem and display the images from folder check this link
http://aspdotnet-suresh.blogspot.com/2011/03/how-to-save-images-into-folder-and.html

Anonymous said...

hi,
i wanted to know how can we delete a row from gridview, so that is gets deleted from the database also..

Suresh Dasari said...

hi,
check this link here i explained clearly how to delete gridview rows using asp.net
http://aspdotnet-suresh.blogspot.com/2011/01/how-to-delete-records-in-gridview-with.html

Donzo said...

Any ideas how ti put data into images that are moving around a web page ? its for non-profit dcollier8@netzero.net

Ger said...

do i need to change the connection string? im still having errors

Suresh Dasari said...

Hi Ger,
Yes you have to change the connection string here i used my db connection you should give your db connection in web.config file

Anonymous said...

hi suresh


any idea to delete the row containing images in the datagridview

manju said...

any idea to delete the row containing images in the datagridview, its giving error in the http handler

Suresh Dasari said...

hi manju,
Check this post to delete gridview records

http://www.aspdotnet-suresh.com/2011/01/how-to-delete-records-in-gridview-with.html

Here we are inserting images in database so if we delete record in database that is enough. Here you need to remember one point that is after delete record again rebind your gridview with latest data.

manju said...

thanks suresh

i got it

Ted said...

i try to use the delete gridview record for the images but it does not work. any ideas about this error?

ArgumentOutOfRangeException
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

ramesh said...

Hi suresh,

I am working with Image web gallery so I am trying to use jquery uploadify to upload images and store them in folder and at the same time I need to save them to sql Server database.But I am failing in doing that Can you do me an article regarding that.So that I need to resize the Images while uploading an save them in seperate foldder and the original one's in another folder.And I need to display those Images after loading using list view or gridview as you did.if you give me any ideas that will be very helpful to me.

ramesh said...

This is my handler code:


public class Upload : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];

string savepath = "";
string tempPath = "";
tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
//tempPath = context.Request["folder"];
savepath = context.Server.MapPath(tempPath);
string filename = postedFile.FileName;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);

postedFile.SaveAs(savepath + @"\" + filename);
//Fileupload.UploadToDatabase(savepath + @"\" + filename);


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ImagesConnectionString"].ToString());
//Open the database connection
con.Open();
//Query to insert images path and name into database
SqlCommand cmd = new SqlCommand("Insert into Image(ImagePath) values(@ImagePath)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("@ImagePath", filename);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();


context.Response.Write(tempPath + "/" + filename);




//context.Response.Write(filename);
context.Response.StatusCode = 200;
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}


}



public bool IsReusable {
get {
return false;
}
}

Anonymous said...

hii...sir
h r u...
your site is very nice.....
sir i hv used the asp.net3.5..and when we try to add the httphandler file to my project .....then we can no got up this file in ADD new items template ....from where i can add it to my project

Robin Raghav said...

sir i have an exception in httphandlarfile.........at line(SqlDataReader dr=Connection.ExecuteReade();).....Exception is "incorrect syntax near"=" ";

Anonymous said...

hi, this code is working fine if we use asp.net empty website, but if we are using asp.net website template we are not able to call .ashx file itself, please help me out , thank you

ahobul said...

hi, this code is working fine if we use asp.net empty website, but if we are using asp.net website template we are not able to call .ashx file itself, please help me out , thank you

Anonymous said...

Why would I be getting a box with red X instead of the images?

manju said...

hi suresh

give me some ideas(some reference links) to create table dynamically and adding the rows also dynamically with prevoius rows data.............

sonu said...

hi this is sonu ,i have used this code,codes are running bt images are not comes across the name field,it is unable to show image in data list.except it all things are working properly.i used to generic handler,i am using windows7,visual studio 2010,and .net4.0.whats the problem plz suggest me.
sonu new delhi.

Shambhu said...

Thanks very much suresh jee your website is very helpfull for developers.

Shambhu said...

Will you please tell me in bigger project which image save method we should use in database using image database or using folder upload classical method. Please describe the difference in performance while comparing both.

indrajeet said...

Great. It is too much helpful for me.

Jay Patel said...

i want upload image and save in database then i want to give a link to each image for example :- when i click on img1 it redirect page on its detail page and when i click on img2 it redirect page to its owan page.

felix said...

i need display video from database in asp.net

SIMANTA said...

Hi suresh

I am simanta, i am a web developr.I am stucking with one problem. Please help me sir,
I want to dispaly images dynamically in gridview and simultaneously i also want to put some data in 2 textbox. When image change the value inside the textbox should also change. The image should change in a regular time interval.

With Regards
Simanta Jyoti Medhi
+919538804164

Anonymous said...

i am Ajay Yadav. I am trying to upload an image in my website folder and saved its path in my database. I search it on internet but not able to do this. Plz help me. And send me at akylucknow@gmail.com

Suresh Dasari said...

@Ajay Yadav
check this post to save images in folder and images path in database
http://www.aspdotnet-suresh.com/2011/03/how-to-save-images-into-folder-and.html

Ujjwal said...

Hello Suresh Sir..

I really liked the Article. I read too many articles about saving images in DB but this is the simplest and easy to understand. thanks.

Also i have a query how can i add java script ( like On mouse over a particular image the image should be shown in another panel) to the images that i am retrieving in my Datalist from database.

I have the java script to do it but don't know how to do it on images that are dynamically retrieved.

yuva said...

hi sir,
If i am insert the picture into the asp web page ,i can able to write the text in next line only.if i want to write the text into the side of picture means what can i do?...

yuva said...

hi sir,
If i am insert the picture into the asp web page ,i can able to write the text in next line only.if i want to write the text into the side of picture means what can i do?...

kiran kumar said...

i wrote the code step by step as you said, but it is showing error "ImageID could not be null"

2) i changed the property value of table as ImageID set to null values true. and i debug it , then it is storing images showing message "saved successfully" but if i check in table , imageID is showing empty.
3) and in gridview control, the image control doesn't showing the stored image, it is showing like breaking image control.
why i am getting these errors? give me the solution pls

Suresh Dasari said...

@kiran,
In table design i said we need to set the Identity Property true for ImageID column once we set whenever insert record automatically ImageID column fill with value(like 1,2,3...) otherwise you need to enter values manually. I think you forgot to set the Identity Property for ImageID coulumn and check your images path.

suresh said...

how can we write mouse click event for the datagrid images column.
my requirement after clicking that image it has to open in a new window in full size

Suresh Dasari said...

@suresh
check this post it will helps you to solve your problem here i explained clearly how to show image in lightbox whenever we click on image in gridview
http://www.aspdotnet-suresh.com/2011/03/display-gridview-images-with-lightbox.html

Anonymous said...

hello sir,
ur all articles r very nice n helpful
sir i want to upload multiples images against one UserID in the database and show all images in gridview. i want add button for multiple uploads
can u send me the demo code on my id manindra.tayal@gmai.com
plz help me

nagendra said...

hi sir,
ur blog is very helpful.
how to edit records in gridview & upload images using insert&update commands in asp.net?
plz help me?

Nityanand Yadav said...

Nityanand Yadav said


I am regular user of your website . This really Helpful... . i have no word to explain it.

kunal said...

may i use this on vb.net project then how i add http handler page or which page or method is used instead of http handler

Anonymous said...

hello suresh,
I am sushil. I am able to store the image in database in varbinary format. but the problem is while retrievin it. I am using linq to entity style. so will be there any change in the logic of retrieving. i have tried context.response.binarywrite but its not working

chandan said...

iam chanchal singh
my problem is that all my user not having img in our database only some user have img so that if img is not in our database than only default img is show and img is present then their img show.

Anonymous said...

i m akash
hi your whole code is working properly but the problem is inserted images are not shown in the gridview..

Praveen said...

Sir i want that image should be compressed while uploading in database.

shyam said...

hi sir... i am very new to the asp.. presently i am working with the gridview..can we insert data into the gridview with out any ado .net architecture and taking autogenerate colums=false...if yes can you please help me?

Anonymous said...

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Anonymous said...

sir,Im new to .net,i compiled the above source dnt get any error but while running it says
Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 14: public partial class WebForm5 : System.Web.UI.Page
Line 15: {
Line 16: string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
Line 17: protected void Page_Load(object sender, EventArgs e)
Line 18: {

aarthi said...

sir am getting the following error when i compile the above code please help me
Both DataSource and DataSourceID are defined on 'gvImages'. Remove one definition.

Anonymous said...

What Namespace should i add to get the configuration Manager

surendar said...

i have used this code ,image is saved but it is not retrirv.

it will be displayed error message like.

Error 1 Type 'Handler' does not inherit from 'System.Web.IHttpHandler'. F:\surendar outlook\WebSite5\Handler.ashx 1

what should i do.

Himanshu Pandey said...

Hi suresh
i m a newbie in asp.net..I am a avid user and a great fan of yours,love to read your posts.Please tell me how to give this functionality of inserting comments and displaying them one by one,as is done above..please i have to implement it in my project
Regards
Himanshu

Suresh Dasari said...

@Himanshu Pandey..
check this post here i explained clearly how to save and display comments

http://www.aspdotnet-suresh.com/2012/01/repeater-control-example-in-aspnet.html

Himanshu Pandey said...

Hii suresh
Thanks for your reply.I m much elated and thrilled when i saw ur reply for me.Thanks
I gone through your post,but i also need to show small profile pictures of the ppl along with their comments???Please do help me
thanks again
regards
Himanshu

Himanshu Pandey said...
This comment has been removed by the author.
Himanshu Pandey said...

Oh suresh,its done.Its 2:30 am morning and i am still Gearing up with your post,trying to add profile of users along with their comments from database,and finally its done.
Thanks Suresh for your for your quick reply,which helped me to reach my way.This bespeaks your kindly heart.
One more thing i wanna ask you,though i practiced the same in sql server Db,but i am using mysql db in my project,so the same code will work??what is the datatype to be used in mysql for storing images?
please always keep in touch.
Regards
Himanshu

Ajay Patil said...

sir i'm unable to retrive images ...there is no error ...gridview images are blank

poonam said...

Hi,
your code is excellent but its can't work with web application got error fileupload control doesn't exist in current content.

poonam said...

Hi,

can u please tell me how to give transaction of image ie i want to do the slideshow with effect

pls help me

Jonathan said...

Simply create datatable with image column and add image to it

dtMain.Columns.Add("ImageColumn", typeof(Image));

dtMain.Rows.Add(Image.FromFile(photopath + "1.jpg"));

Download full code at http://tablegridview.blogspot.in

Suresh Dasari said...

@poonam..
this sample i did using web application only it will work as web application and for slideshow effect check this post http://www.aspdotnet-suresh.com/2011/12/jquery-lightbox-image-slideshow-gallary.html

Unknown said...

lokesh said....

it's gud but can u say simple way to insert a img from sql db and retrive from sql db

rakesh b.k said...

Thanks mate :)

Kodexpression said...

sir can u tell me how to rotate the ImageButton Control....????

Anonymous said...

hello sir i m getting error that, "The name 'ScriptManager' does not exist in the current context". plz sir tel me solution for this

asmita said...

hello sir my image is not getting display.........plz sir tel me solution on it......as soon as possible

jigu said...

can u give me ur contc no.

Pooja said...

hello,....Please tell me how to give connectionstring....thank you...

Suresh Dasari said...

@Pooja..
i updated post by adding connectionstring also please check it once.

Anonymous said...

Hi Suresh,
I am pradip
In gridview I want to show 3 Columns.In first column (Cell) image,In 2nd column(Cell) one linkbutton and information and in 3rd column (Cell) informtion(static).
I am able to insert image into 1st column
but unable to insert 2 columns info
Please give me solution as soon as possible
Thanks in advance.

trinadh said...

hi suresh this artical helps me lot thanks..n i need more explanation about images and videos storing in databases please help me...

Anonymous said...

MY IMAGES ARE NOT GETTING DISPLAYED CAN PLEASE GUIDE ON THIS ?

Seema said...

Why these pics wont display.... i really exhausted.. plz guys somebody help me ... i have followed the steps exactly.. and downloaded these attached file and compared it with mine .. but it still not working ..

the code i working properly but the images don't display .. it shows red "X" instead.

plzzzzzzzzzzzz help me.

Seema said...

finally i found the solution..

for those who r facing a problem with displaying the image .
you just have to add a new webForm and do the retrieve process through it.
don't combine both of codes(store image and retrieve image) together in the same form..

copy this code for binding the data in the gridview, and past it in the form load of the new webForm(to retrieve the image) and design a gridview as specified above ... instead of writting the function of binding the data for the gridview in the form of storing the images.

that's it .. hope i was clear in explaining it

Anonymous said...

i have used this code,codes are running bt images are not comes across the name field,it is unable to show image in data list.except it all things are working properly.i am using windows7,visual studio 2010,and .net4.0.whats the problem plz suggest me.

Unknown said...

Image is not store in sql database as a binary data i want to store in data base as well as in a folder. do you have any idea about that ?

Suresh Dasari said...

@Sunil Acharya....
check this post to save images to folder
http://www.aspdotnet-suresh.com/2011/03/how-to-save-images-into-folder-and.html

adi said...

i am able to upload the files into server but i am unable to view the images in the browser.
instead of image it is displaying [x] in red color

adi said...

@seema can u upload ur file and share the link here

adi said...

@suresh
can u tell me how to display only single image based on drop downlist selction

Suresh Dasari said...

@adi...
if you are getting cross mark means please check your handler code whether you are getting data from database correctly or not and to display image based on dropdownlist selection means you need to pass image id then get those record details from database and display it on your page.

adi said...

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

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

public class ImageHandler : IHttpHandler {

string con = ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImageID"];
SqlConnection connection = new SqlConnection(con);
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();
}

public bool IsReusable {
get {
return false;
}
}

}

Anonymous said...

Hi I getting this error what should i do now ? antone expain this error.........!NullReferenceException Was Unhandled by User Code

Anonymous said...

Hi suresh,

Iam getting error while loading gridview

http://aspdotnet-suresh.blogspot.com/2011/01/how-to-delete-records-in-gridview-with.html...

kindly assist me..

Naveenkumar chemutu

Arun.P said...

Hai suresh thank u so much.

Arun.P said...

suresh, how to upload video files and how to view that videos in asp

Anonymous said...

Thank you so much mate it had been really helpful god bless you

vivek said...

there is no error in my code but image is not showing in gridview it dispalys as a blank.

vivek said...

what is the best way of sending cintrols values from one page to next page and next page to other page by button click and submit it on this page..(as like registration of more than one page )..plz rep it.........

Anonymous said...

Hi sir,I am clicking on upload button i am getting an error ,Server error / website application HTTP 400 Bad request can you please suggest me how to remove this error?

Junz Tan said...

Hi suresh,
After I upload the image, it cannot display the image at the gridview. Please help. thank you.

SAGAR BHOGALE said...

how to upload video and save it in database and retrive from database and play. please give me the code in c# asp.net my email id= bhogale.sagar1@gmail.com

Aswini said...

hi sir
why we are giving ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' this url in grid view i cant get it will u explain with any other logic.

Aswini said...

hi sir
why we are giving ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' this url in grid view i cant get it will u explain with any other logic.

Kodexpression said...

Sir how to show binary image from database in repeater?

Anonymous said...

hai suresh
in grid view you are selecting only two columns what about image column

Anonymous said...

sir,
i have an problem
when any user form fillup his/her registration purpose, he/she also have to uploaded his/her picture and when he/she logged in the account then he/she can see his/her image as the home section.
i want to make profile pic
can u tell me sir...............
how i will do it

Anonymous said...

hi

Anonymous said...

Sir,the above code is running error free,but I am unable to view the images.I am only viewing the image name but not the image in the gridview.Please help Suresh sir.

Life with Saheli said...

Sir,the above code is running error free,but I am unable to view the images.I am only viewing the image name but not the image in the gridview.Please help Suresh sir.

Anonymous said...

i got error like this "object must iconvertible" what is the solution for this....

jitenderkapil said...

hey how to retrive particular binary image from SQL server in asp.net using C#. when i search image throu text box.

Anonymous said...

Can you make video tutorial for this

Anonymous said...

Dear Suresh Sir my problem is upload Photoimages in KB.MB like bank apply online form it will only genarate 50MB give the full source and cs and other problem photo image in dimension...

Anonymous said...

HOW TO SEE IMAGE FROM NORTHWIND DATABASE IN ASP.NET USE C#,PLZ HELP

Unknown said...

Hi it is very nice article but when run this code take me this is error
"
Cannot insert the value NULL into column 'ImageId', table 'DressDB .dbo.Image'; column does not allow nulls. INSERT fails.
The statement has been terminated."
please what i can do
thanks alot

Anonymous said...

creating tabs dynamicaly using juery

Anonymous said...

Hi Suresh,
Keep the Good work going.

I have a similar DB as you have shown except in my assignment I have to use varchar type to store Img path rather then the img it self in the database.

Now using the Grid itself I have to Add the add the img by browsing to the img path and then on "OK" I have to show the img in the grid rather then its path.
A hint that I had got from my Faculty is use a File Upload Control.
Now I am really saturated trying to figure it out...

Anonymous said...

its really wonderful buddy thanx a lot

ၾကည္ျမန္မာ said...

Sureah,

What happened to me? When I create your code, I can input image to database, but they are not come out.

When I downloaded and ran your code directly (a little change for database connection), I got 8 errors concern with image name textbox, upload box and gridview are not current context.

When I run update, delete, edit program, I can run directly according your code.

Any help for me, pls.

a said...

dfs

Unknown said...

you can do 1 thing that somehow try to get the file extension of an uploading file and compare it using if statement
if(extnsn=="jpg")
{
code to be executed
}
try that .....well i am a beginner but dis could work.....
if u find it useful then comment

Unknown said...

how to send session(or)querystring data from one page to multiple pages in asp.net

shanti said...

Can you send more tutorial for this..... plss

Unknown said...

Hii Suresh Sir..
this is jp..
can you please tell me how to use the httphandler in our project because when I am retrieving he image from database in the grid view there is no error but it is not showing the image.
please reply ASAP....
thank you in advance.......

kannan said...
This comment has been removed by the author.
kannan said...

i need one help suresh,can you please tell how to use print option work in firefox...

Mahaboob said...

Hellow sir,
I implemented ur code but im not getting accurate result. i.e im getting imagename, imageid, but the image is not displaying. In gridview the image is displaying in error image format.
Please give me answer what is the reason? and what is the solution. please reply me. thank u somuh.

Unknown said...

Sir i am unable to understand that how to add httphandler in my project kindly help me in this regard

Anonymous said...

can u tell how to create stored procedure

Unknown said...

Hi it is very nice article but u have to update one thing there is a generic handler behalf of httphandler in asp.net 4.0 . and really good article keep it up

Anonymous said...

hi sir,
i am raju i want to retrieve image from gridview to image control in asp.net plz help me

Unknown said...

Hi ...Sir

I took support of your code ...Its nice

I am facing difficulties to show image in gridview

Grid view only displayed Image name not image

Unknown said...

hi ,
i m sivi . i having employee login and logout table using oracle.
here login and logout time problem. ex
21/01/2013 9:15:10 AM
21/01/2013 6:45:23 PM
21/01/2013 6:46:41 PM. this is prob. i need first entry and last entry then calculate the working hour . ple help me. i m eager to waiting for your replay

Saurav said...

HI Suresh. This post was very helpful for me for my project. Now i have a query that u r passing parameter like "cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;" on the page itself but i have created a class and i want to pass the imgbyte parameter to class like "objClass.imgbyte" but it is giving an error. So can u pls help me how to pass parameter of byte[] type to class

Anonymous said...

Hi Suresh,
Your site is really good.I wanted to know how to display the column value from database into the label box after inserting successfully.

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

I'm really enjoying the theme/design of your site. Do you ever run into any browser compatibility problems? A few of my blog audience have complained about my site not operating correctly in Explorer but looks great in Chrome. Do you have any recommendations to help fix this issue?

Here is my page credit cards

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Kesavakumar said...

hi Suresh,

Your code is working fine, except image. Instead of grid view I'm using data-list in that i'm getting all data even for image url also like this("ImageHandler.ashx?ImID=5"), data what it is fetching is correct but image is not getting displayed through image handlerfile. This image handler file not get fired only in this datalist. same datahandler I used to display image once i upload a image by that time it is working fine, please guide me how to display image in datalist.

Anonymous said...

this example is very useful

neha sharma said...

Hi dear,, you are too good i am just a beginner and your posts helps me a lot and easy to understand too ..thanks a lot really u r too good..

Unknown said...

hi.. i want to know how to match an image with a stored image in the database.

Anonymous said...

How To update Binary data image in database...????PLz help me out

Anonymous said...

sir ,i have used this code but sir still problem havebeen arise.when we run the webpage it insert the image in database sometimes but it doesn't show imgaes in gridview,no error is occur at the uploading the image

Regards,
ashutosh kumar

Naina said...

Thanx for the idea

m said...

images uploded but not showing in grid view please help

Rohan Tangade said...

Hi Sir.
I want to create a search box for students,means suppose i type 'Rohan' then it must show all students whose names ara rohan in asp c#...
Thanking you
Rohan

Unknown said...

hi sir i want to compare two car model wise like audi a4 and swift dezire... how i compare??? plz give response..yhank u in advance sir

nandy said...

I don know what to say, but one this is Suresh, thank you verymuch, bcoz of your site, so many of us learnt many things. ppl who are outt there plz learn from this site, you ll make yo task easier.

Once again, Thank You.

Anonymous said...

Will the code work without these lines?
HttpPostedFile img = fileuploadImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);

Bcoz we are not using img anywhere in the code?

Unknown said...

hello sir,
after inserting the images i was unable to view the grid view. Help me.

Anonymous said...

Error occured when ConfigurationManager is used..

Anonymous said...

hello sir,
Images are not visible in gridview only the names of images are visible..why so?

Anonymous said...

Hello,
Can't we put the fileUpload control in the gridView and acces it????
Am not able to bing the image dynamically in gridview by directly putting the fileUpload control in grid View... Sir Please can you help me...




My Code is...











Anonymous said...











Unknown said...

image are uploading but not Displaying on page...

an error was there saying that:--

SqlException was Unhandled by user code
Incorrect syntax near '='.

at Imagehandler.ashx.cs file at the line of:-

dr = command.ExecuteReader();

please give me solution

Ani said...

Thanks a ton...Your site is really helpful. Finally able to upload images using ASP .NET.

But I can't understand the GridView part...Do you have a tutorial of how to display images in datagridview control in ASP .NET?

Ramesh Babu said...

thanks...
And
I have one question...
How to divide image into blocks ?

Gaurav Agarwal said...

how can i create image gallery?
plz tell me, my id is gauravpansari1991@gmail.com

joshila said...

Hi sir,how can i create image gallery?how to edit or update image in database??pls help me...

Anonymous said...

Hello! Sir, do you know how to fetch the latest image uploaded to the database to be displayed on the homepage?

Anonymous said...

your blog is very useful... Thank you..

him2cool said...

hi suresh why this problem comes- Cannot insert the value NULL into column 'ImageId', table 'ImageDemo.dbo.Image'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Bharat said...

hii bro.
it showing error "server tag is not well formed"
at

Anonymous said...

hello sir, there is a problem when retrieve images from database. also you did not explain what namespace should be use. Please tell me the above code and also tell using HttpHandler file does need configure in web.config file. thanks

Anonymous said...

Hello Sir,
I have a problem. I am developing a website using .NET 3.5(lang C#) and WAMP server MySQL as a backend. I want to store and retrieve images from database. I can store the images in database successfully but I am not able to retrieve the images. Plz help me in that sir.

I am a regular follower of your blog. Plz help me.

Thank you very much in advance.

Anonymous said...

Hi, i want to save file from front end to database (varbinary field) and retreive using object of the businness class(using hashtable to pass data)

Unknown said...

can u suggest me..
how to add image into gridview from folder ...
please give me solution for this
thank you

Anonymous said...

sir i am tried this code but the image is not displayed in grid view because u could not explain about imagehandler.ashx in this part so plz update it
thank u sir

Unknown said...

hi suresh sir , here i want to export images in excel format but my images are stored in binary format in database , how can i get it using c# code ............................................................................................................................

Unknown said...

ArgumentOutOfRangeException
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
every time getting the same error plz help me suresh.
why exactely this error is coming?

Anonymous said...
This comment has been removed by the author.
Anonymous said...
This comment has been removed by a blog administrator.
Mathi said...

Instead of loading the DataTable from DB I'm hard coding it and tried to display images which is not working for me. The images are not loading for me. Below is the only code change I've made. Please help me.

dt.Columns.Add("imagename");
dt.Columns.Add("ImageID");


DataRow dr = dt.NewRow();
dr["imagename"] = "Image1";
dr["ImageID"] = @"D:\Mathi_Working\01816_Backup\Mathi\Images\9.gif";

dt.Rows.Add(dr);


DataRow dr1 = dt.NewRow();
dr1["imagename"] = "Image2";
dr1["ImageID"] = @"D:\Mathi_Working\01816_Backup\Mathi\Images\HereSmiley.JPG";
dt.NewRow();
dt.Rows.Add(dr1);

Anonymous said...

I like much your website. Thanx for valuable coding.

Anonymous said...

Nice blog.. Thanks for providing the information how to insert images into database and how to retrieve and bind images to gridview using asp.net and how save and retrieve images from database using asp.net. Really it is a very useful blog!!

Convert Image

Anonymous said...

hey
hope you are fine. your code of retrieving image is not working fine for me.images are being displayed in the cells of data table.

Anonymous said...

i am using following code to insert image in database........image path is saved in database and also image is saved in picture folder.........but i dont know how to fetch image from database using similar code
if u can please help me

protected void Button1_Click(object sender, EventArgs e)
{


con.Open();
if (FileUpload1.HasFile)
{
String photo = "~/picture/" + FileUpload1.FileName;
FileUpload1.SaveAs(MapPath(photo));
{
String pic = "~/pic/" + FileUpload1.FileName;
cmd = new SqlCommand("insert into wpt values ('" + TextBox1.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + DropDownList1.Text + "','" + DropDownList2.Text + "','" + DropDownList3.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + DropDownList4.Text + "','" + pic + "','" + TextBox5.Text + "')", con);
cmd.ExecuteNonQuery();
//Response.Redirect("registerredirect.aspx");
}
}



}

Anonymous said...

sir,
I require a code for creating an ivr application using asterisk.

Unknown said...

i tried ur above given code but an error throwing

Error : Type ImageHandler does not inherit from System.web.IHttpHandler

If u hv any idea please update soon,
thanks
Amit

Anonymous said...

Hi suresh,

can you write code for:- Insert video file in database and then show on page. i have searched a lot but could not gate proper code. Please write code for us. I am frequent visitor of this site

Thank You
Reena Singh

Unknown said...

Hi Suresh,

I want to upload a video file using c#.net.Save the uploaded file in SQL database. The uploaded video and its thumbnail shown into grid view. When user click on thumbnail they can play it. Please suggest the better solution.

Unknown said...

I getting group of images for particular ID(VehicleID),,,it returns 3 records...but same image is binding three times....

Unknown said...

hi please help me
my image save in sql in binary format.
i want to retrieve it in image box.
my query is select img from userprofile where username=@username

Anonymous said...

i need code for complete login page with db also for forgot pwd.thanq

Anonymous said...

getting error
says that- Incorrect syntax near @imagedata
plese help...please...

projectdatasp@gmail.com

Unknown said...

Mr Suresh Sir How to insert Multiple Record in One Click Plz Help Me

R.s.v.v. Prasad Rao said...

Sir, How can i pass textbox value in the query string given in the image tag of aspx? plas help me sir

Anonymous said...

Hi sir,

I want to dispaly image in gridview. But i am storing images from one webpage and storing in sql server dbtype is image.
i want to retrieving form database and show it an other web page in gridview..

Unknown said...

Sir, Namaskar
i am using VS 2010 and ms sql server 2005. Here I m facing a type convert problem. pls solve it.
error is:

Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.

Source Error:


Line 44: cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imagename;
Line 45: cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
Line 46: int count = cmd.ExecuteNonQuery();
Line 47: connection.Close();
Line 48: if (count == 1)

Source File: c:\Users\rakesh\Documents\Visual Studio 2010\WebSites\RuhilTech\image.aspx.cs Line: 46

Abhinav Malviya said...

everything is fine but my sotred images not dispaly in image folder.
i hv already use httphandler,ashx file.
i hv to follow all ur instruction but all worked successfully but images not display..plz give us positive answer...

Unknown said...

sir,I Have two tables and i am displaying the datas using a gridview by using view in sql server i need to implement drop down search thats all are working fine but i need to Change in this by using login form when a user logins his username gets saved automatically by using session but while i am displaying in grid i am getting this username its the id we have given for the corresponding user but related to that id i need to match the correct username thats given in another colomn in login table and needs to display in gridview can u please give me a idea how to implement this. Iam trying from last 2 days not getting please help me....

Unknown said...

hello sir,
my name is saurabh gupta
i have a problem can u help me out that problem
sir i save the image path in database and image store in a folder
but it will not retrieve at the time of page load sir please give me answer
thanks sir...

Anonymous said...

sir your blog is a great help for student like us, but some of your demo are not working pls make them work they are very beneficiary in understanding the concepts

Unknown said...

hello sir,
how to display the images using datalist control and for the corresponding id[row].

Unknown said...

sir,
how can we insert new row using data grid view without textbox controls. for ex. using add command to insert new record within gridview.
so please give me code sir......

Sandeep said...

Hi,
I was able to load the image on the page using this however the handler.asps/.ashx is running when the current page lifecycle ends (i.e. after the page load completes). In my case I am creating the image control dynamically(there can be multiple image controls) and I need to fetch and bind the images corresponding to each control. Using the above technique only the last image URL gets assigned to the image control, the rest of the images show up blank. Can I get some help on this?

Anonymous said...

working well thanks

Unknown said...

HI Suresh,
How to retrieve image from file path stored in database display into listviewt using asp.net

Unknown said...

hi sir,
I am completely confused regarding "how to retrieve an image from database on clicking imagebutton present in a gridview"
Thanx in advance..

Unknown said...

hi sir,

Thanx for such a valuable response.

The Online Income Insider said...

thanx

Anonymous said...

Can Anybody explain me what is the use of handler.ashx file with an example. please show me a scenario with and without use of handler.ashx file. plz i need it immediatly.

Cool_Coding said...

I am working on a windows application that will store customer data along with image,
I have done the part of uploading a image. Now I want to write a code that will work as like download link in web applications.
How to save uploaded image data back to computer?
Here is code i used for upload

private void btnUpload_Click(object sender, EventArgs e)
{
try
{
string str = ConfigurationManager.ConnectionStrings["MySampleDBConnectionString"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(str);
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpeg;*.bmp;*.png;*.jpg)|*.jpeg;*.bmp;*.png;*.jpg";
if (open.ShowDialog() == DialogResult.OK)
{
txbImg.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
}
btnSave.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message.ToString());
}

Unknown said...

How can i add the HTTPhandler.ashx class in visual studio 2008? plz help..

Murari said...

Dear Suresh , I try this post's code on Visual studio 10.
http handler giving syntax error near reader.
what change should i made in that.

Thanks in advance.

Unknown said...

I came to know many things about .net only from your posts suresh. Thanks a lot . . . . U R doing a good job

«Oldest ‹Older   1 – 200 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.