Table schema is shown below, ID column is primary key with Identity increment,datatype of Image column is Binary.
To know how to save or store Images in DataBase visit link below
Upload/Save Images in Database using FileUpload Control in ASP.NET C# VB.NET
For displaying images in gridview we need to create a Handler to read binary data from database.
Right click on solution explorer and Add new item, Pick Generic Handler and name it Handler.ashx.
Write this code in ProcessRequest method
C# code behind
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ImageName,Image from Images" +
" where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter
("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}
VB.NET Code
Public Class Handler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext)
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings
("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select ImageName,Image from Images" +
" where ID =@IID"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ImageID As New SqlParameter
("@IID", System.Data.SqlDbType.Int)
ImageID.Value = context.Request.QueryString("ID")
cmd.Parameters.Add(ImageID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite
(DirectCast(dReader("Image"), Byte()))
dReader.Close()
con.Close()
End Sub
End Class
Now drag a GridView control on the aspx page and add SQLDataSource to it.For configuring GridVIew with SqlDataSource read
Insert Delete Update records in GridView using SqlDataSource ItemTemplate and EditItemTemplate
Now go to html markup of GridView and add a TemplateField and in ItemTemplate add a Image control to display Images.
Html Source of GridView should look like this
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" /> <asp:BoundField DataField="ImageName" HeaderText="ImageName" SortExpression="ImageName" /> <asp:TemplateField HeaderText="Image"> <ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [ID], [ImageName], [Image] FROM [Images]"></asp:SqlDataSource>
For VB.NET there is slight change in html markup of page
change below mentioned line
to
change below mentioned line
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
to
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")%>'/>
THis is how it will look
If you want to display Images in multiple columns or in more than one clumns of GridView then u need to make changes in the code as mentioned below.
1. Add a new column in database (i've named it Image2)
2. Add one mote Template Field in html source of gridview and change source as below
<asp:TemplateField HeaderText="Image"> <ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=1"%>'/> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Image2"> <ItemTemplate> <asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=2"%>'/> </ItemTemplate> </asp:TemplateField>
And make these changes in code behind of handler.ashx
//Add this line of code in handler.ashx
int intImg = Convert.ToInt32(context.Request.QueryString["img"]);
//Now change earlier code to this one
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
if (intImg == 1)
{
context.Response.BinaryWrite((byte[])dReader["Image"]);
}
else if (intImg == 2)
{
context.Response.BinaryWrite((byte[])dReader["Image2"]);
}
dReader.Close();
con.Close();
Now it will look like this hope this helps.
Download sample code attached

Sample code for displaying Images in Multiple columns

Other GridView articles:
ASP.NET Display Images in Gridview/DataList using objectdatasource
ASP.NET Insert Edit Update GridView with ObjectDataSource
Add AutoNumber Column in GridView or DataList
Creating Shopping cart in ASP.NET C# VB.NET Example using DataList GridView
Ajax autocomplete extender textbox in EditItemTemaplate of GridView
Your Post is not visible...
ReplyDeleteI Need your help for My blog..can u give me your email address so I tell you my problem...
regards
your tutorial is too much helpful...thnks a lot...
ReplyDeletebut just one problem....
how to display a particular picture depending upon the id....
i have changed the id value as a integer (handler.ashx?id=3)....
but the output is 2 same picture with id=3...
the no 2 is the rows in my database value ....
@GORA..........ROCK THE WORLD:
ReplyDeleteI am not sure what actually you are trying to do any way i've created a sample for you
I hope this is the functionality you are trying to achieve
Download from here
Do let me know if you intended something else
thanks a lot ....amit...
ReplyDeleteactually i just miss the single line of code...
gridview.databind();
thats why not getting the desired output...
thanks again
at handler.ashx, error message on
ReplyDelete"Parameterized Query '(@Img_Id int) SELECT Img_Content, Img_Type FROM ImageGallery expects parameter @Img_Id, which was not supplied"
please help me out on this one, thanks!
@Anonymous , u r not supplying Img_ID in ur query ,
ReplyDeletePlease post full code of handler.ashx with select command so that i can look into or full
This comment has been removed by a blog administrator.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteHi Amit,
ReplyDeleteWith regards to my first comment, this is actually the errors i'm having in the Event codes and saying "Type ****** is not Declared"
* SqlConnection
* SqlCommand
* CommandType
* SqlParameter
Thanks in advance for any assistance. :)
@edgecrosser:
ReplyDeleteYou are missing namespaces ,
Please add these namespaces in code behind
using Syatem.Data.SqlClient;
Hi Amit,
ReplyDeleteAh yes I forgot the namespaces, thanks!
hi Amit, its me again,
ReplyDeleteI made all the syntax errors free but there's one thing left in the Handler.ashx file that I can't configure.
There an error in the line "IHttpHandler" and it says that Class 'Handler' must 'Sub Process Request(context As HTTPContext)' for interface 'System.Web.IHTTPHandler'.
Thanks in advance if you could help me on this
Hi Amit,
ReplyDeleteI tried to debug the program, and I got this build errors:
InvalidCastException was unhandled by user code
Conversion from string 'Handler.ashx?=' to type 'double is not valid.
Hope you could help me on this :)
@edgecrosser:
ReplyDeletePlease write your code inside below mentioned method in handler.ashx
%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
//Your code here
}
For the InvalidCastException error please make sure that ID field in database is numeric and write exactly same code mention below
ReplyDelete<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
Hi Amit,
ReplyDeleteSorry for responding late. I will follow your advise and let you know if it worked already. Thanks!
Hi Amit,
ReplyDeleteI just checked the latest thing you advised to me on the Handler.ashx code. You gave me a C# coding, but I'm trying this on VB.net
Looking forward again and thanks!
Hi Amit,
ReplyDeleteIt's me again. I tried to run the program again and I got error in this line:
error: Conversion from string "Handler.ashx?ID=" to type 'Double' is not valid
and i got that from the command u advised me on #15 of this thread (i'm having errors why putting the code here)
Please advise me on this. Thanks in advance again.
@edgecrosser
ReplyDeletehi please download the VB.NET sample code from link below
Download VB.NET code to display images in GridView from Database
Do let me know if you have any further issues
Oh great Amit! I'll try it again and let you know soon :)
ReplyDeleteAmit it's working now!!! You're a savior! Thank you thank you!!
ReplyDeleteHi Amit
ReplyDeleteI have read your article about displaying image from the database and bind it to the gridview it work fine but i have a problem in my table i have 3 column that display 3 images in the same row when i use the handler.ashx and put all the code in the handler and also in source code behind for my page and i use three images in the templatefield but when i bind the gridview three image is binding the grid but all of them is the same it took always the first column in the table:S plz if you can help me my email is waelwehbe585@hotmail.com waiting ur reply
@Above:
ReplyDeleteDOwnload and check sample code from link below
Display Images in Multiple columns of GridView from DataBase
Do let me know if it solves your query or not ?
Dear Amit
ReplyDeleteThanks a lot for your reply this sample same to work fine but its problem that it goes two time into the database in my case i have to display 3 images per row so its bad for the performance of the application do we have another choice to display the 3 images in one select statement and one handler.ashx many thanks good job waiting ur reply
@Above:
ReplyDeleteI've update the code in article to display Images in multiple columns of GridView using single handler.ashx
You can download and check the sample code attached in the article.
do let me know if it solves your query or not ?
Hi Amit
ReplyDeleteThanks a lot for your response ur code work very good and its better from the first released but i have change the way that i saved my picture i am saving them in a folder not in the database any more
Good Job
wael
@wael:
ReplyDeleteIf you are saving Images in a folder then you can read my article mentioned below
Display Images in Gridview/DataList using objectdatasource
Hope this helps
hi sir !
ReplyDeletewhen i implement your coding it run succussfully but image is invisible in the gridview pls help me my mail id--pardeepbeniwal84@gmail.com
@Above:
ReplyDeleteyou may not have saved images in your database properly, tha's why images are not getting displayed
Try ur code with the database i've provided in my code , and do let me know whether it works for you or not
Hi Amit,
ReplyDeleteIt's me again and I need another tip about this. Can you suggest me a link on how to properly deploy the project including the settings in web.config, app.config (where to locate it), table adapters etc. Because right now I'm done with everything but the server is throwing errors about my table adapters. I developed the site using only visual web developer 2008 and there's no publish option.
Thanks again for your help, I appreciate it really.
@edgecrosser:
ReplyDeleteHi edgecrosser, thanks for visiting again
Please refer links below to know more about how to publish and deploy website in Visual web developer
http://msdn.microsoft.com/en-us/library/5c12ykae%28VS.80%29.aspx
http://msdn.microsoft.com/en-us/library/1y1404zt%28VS.80%29.aspx
Hi Amit,
ReplyDeleteThanks for the reply. I installed Visual Studio 2008 and build the project I created in visual web developer express 2008. Then I used the Publish utility tool. I transferred some few files to the remote server for testing again, but when I test a page, it is throwing another error about my table adapters, different from the previous error (connection string). I hope you could spare time to look at this:
http://www.aseanautobizmag.com/default.aspx
Thanks for your time.
Hi Amit,
ReplyDeleteBefore anything else, I used objectdatasource to populate data on the tables (used xsd). Do you think I need to create business logic layer for this too? Everything went fine in my development machine but in the deployment (host), its not reading layers (database's tableadapters) and throwing errors when tested. Please let me know if you want to see the whole coding. Thanks again.
I want to display 3 images from a database in one column,but i dont want to use a handler. Asp.net plz help
ReplyDelete....
ReplyDeletedReader.Read();
//Without this line , u recieve an error whentry to save image
context.Response.ContentType = "image/jpeg";
//end
context.Response.BinaryWrite((byte[])dReader["Image"]);
...
i hope usefull
Bye
This has been infinitely useful. Thank you. The only suggestion I have is to update your VB code above with the VB code you have in your download: http://www.box.net/shared/kv3x7ytv6u
ReplyDeleteThanks again.
hi amit,
ReplyDeletecode is working but images are not bind to gridview please help me
Hello Amit,
ReplyDeleteThank you for this code. It has helped a lot. Everything is working for the most part, but I am having two problems. 1)The pictures are not showing on the page, there are red x's in the frame where the pictures are supposed to display. 2)When an image is added to the database it is added twice instead of one time. Please let me know what I can do to fix these errors.
Thanks So Much,
James
Hi Amit,
ReplyDeleteI have some problem in Handler2.ashx
here some error :
context.Response.BinaryWrite((byte[])dReader["a_data"]);
"Invalid attempt to read when no data is present."
can You help me, \
Thanks A lot !
Hi..
ReplyDeleteIt works great !! Thanks a lot
Hi thanks a lot . . .
ReplyDeletehi nice information
ReplyDeletebharatclick.com
Hi, great article. Could you post the code for displaying images in multiple columns in VB? You currently only have that part in c#. Thanks so much.
ReplyDeletehi
ReplyDeleteyour code is really very helpful to me but just one problem, when i click upload button record insert two times in database. help me out for this. thanks very much
hi
ReplyDeletethanks for the code
it is just superb but only one problem when i click update button two times same record get inserted into database instead of one
can u please help me out
Hi,
ReplyDeleteThanks for the article, very useful.
I have done what you showed here plus made thumbnails instead of normal sized pictures. I need to do a right-click, choose "View Image" and be able to view this image in a new tab. For now, when I do this I have many weird characters. Could you please help me out with sorting this problem. I should probably add some code in the .ashx file but have no idea where to start.
Cheers
thanxxx
ReplyDeletekartiki said...
ReplyDelete" Hi,
thanks for the code but there is one problem my upload images are not display in the gridview .
can u tell me whats the problem.i used ur code same at is it. reply me on my mail id "smilygirl_11@rediffmail.com"
Hi,
ReplyDeleteThanks a lot for the article.
I have a database with images with different sizes. How can I make all of them same size before displaying them in my GridView?
Cheers,
Thanks a lot for this tutorial, it has been very helpful. But I have 1 question: since Imaga data type will be removed in a future version of Microsoft SQL Server, it is nowadays strongly recomended not to use anymore this data type. I tried using your guidelines with Varbinary(max)data type but it doesn't work. Can you do another tutorial with Varbinary(max) data type? Thanks a lot
ReplyDeleteHi,
ReplyDeleteThank you for your endless help.
I've tried your codes and they worked well. But I've been trying to do the same with my ASP.NET MVC Application but I couldn't display images in my Application. The .ashx file does not work in my application, would you please instruct me what to do ? Thank you
my email is : foysa1@yahoo.com
Hi, just want to say thanks for this post, finally it does what I want to do.
ReplyDeleteSpent awhile trying to get this to work from copy/paste'in your code but no image displayed!
Then when I download your sample code that worked fine. So after some head scratching and comparing of code the only difference I could find is the missing code lines (from the handler file)
[CODE]
public bool IsReusable
{
get
{
return false;
}
}
}
[/CODE]
seems strange but this is only diffrence I could find between two code files. Does this sound like something that would stop it displaying the image in the gridView?
Cheers, Trevor
Thanks a lot..
ReplyDeleteThanks for the great tutorial. However, I am getting an error when running the VB version: Invalid attempt to read...
ReplyDeleteAny help would be appreciated
I tried this code for MYSQL database but didn't work.. can you help me?
ReplyDeletehi friends,
ReplyDeleteI am using asp.net with c# .
please give me code for insert image in mysql database and display image from mysql database
pls give i am facing problem since 3 days.......
Hi Amit, Cel here. Do yo think I can add at least 5 images in the database as long as I declare them all in the handler and code behind? I'm creating another website and the editor wants to have at least 5 images insertions and youtube link section where I can possible use repeater control. Thanks in advance!
ReplyDeleteHi Amit,
ReplyDeleteCel here, i download the file for Displaying Images in Multiple Column but there its like the code-behind isn't complete., only the 2 handler files. Thanks!
Hi Amit,
ReplyDeleteCel here, i downloaded the file for Displaying Images in Multiple Column but its like the code-behind isn't complete., only the 2 handler files. I'm trying to post at least 3 images in a gridview this time. Thanks!
I tried the codes above Amit but Image2 appears on both column (image 1 & 2). The first image I uploaded for first column is not inserted on the database. Please help :)
ReplyDeleteI tried the codes above Amit but Image2 appears on both column (image 1 & 2). The first image I uploaded for first column is not inserted on the database. Please help :)
ReplyDeleteHi Amit it's me again. I tried the latest downloaded file in the article multiple images and gridview using one Handler but I always get the same image for both column, the 2nd uploaded file takes the column 1 too. I think there's something wrong with my codebehind, as I preview the database, my first uploaded images doesn't attach, only the 2nd one. Maybe I'm missing some command execution. Let me know what you think.
ReplyDeleteThanks for any help, i'm in a new project again.
Just add this code for vb.net in the handler.ashx after line 28 since it is missing.
ReplyDeletePublic ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
hi amit
ReplyDeletei have an error Failed to convert parameter value from a String to a Int32.
imgId.Value =context.Request.QueryString["ID"];
i also try to convert it like this
imgId.Value = Convert .ToInt32 ( context.Request.QueryString["ID"]);
it gives error like
Input string was not in a correct format
plz reply
I would like to exchange links with your site csharpdotnetfreak.blogspot.com
ReplyDeleteIs this possible?
using this code it give me X's instead of pictures in the girdview, I mean it displays red X's(like is unable to open that photo) Any ideas? And also it only runs locally, whenever I try to run it remotely it gives me the error page. Why is this happening? Here is my whole code:
ReplyDelete<%@ Page language="vb" AutoEventWireup="true" Debug=true %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<
script
runat="server"
>
Public Class Handler
Public Sub ProcessRequest(ByVal context As HttpContext)
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings ("AdrianaConnectionString4 ").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select ImageName,Image from upldphoto" + " where ID =@IID"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ImageID As New SqlParameter("@IID", System.Data.SqlDbType.Int)
ImageID.Value = context.Request.QueryString("ID")
cmd.Parameters.Add(ImageID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("Image"), Byte()))
dReader.Close()
con.Close()
End Sub
End Class
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim strImageName As String = txtName.Text.ToString()
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
Dim imageSize As Byte() = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}
Dim uploadedImage__1 As HttpPostedFile = FileUpload1.PostedFile
uploadedImage__1.InputStream.Read(imageSize, 0, CInt(FileUpload1.PostedFile.ContentLength))
' Create SQL Connection
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings ("AdrianaConnectionString4").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO upldphoto(ImageName,Image) VALUES (@ImageName,@Image)"
cmd.CommandType = CommandType.Text
cmd.Connection = con
Dim ImageName As New SqlParameter("@ImageName", SqlDbType.VarChar, 50)
ImageName.Value = strImageName.ToString()
cmd.Parameters.Add(ImageName)
Dim UploadedImage__2 As New SqlParameter ("@Image", SqlDbType.Image, imageSize.Length)
UploadedImage__2.Value = imageSize
cmd.Parameters.Add(UploadedImage__2)
con.Open()
Dim result As Integer = cmd.ExecuteNonQuery()
con.Close()
If result > 0 Then
lblMessage.Text = "File Uploaded"
End If
GridView1.DataBind()
End If
End Sub
hi your code is workin..
ReplyDeletebefore i didn't remove these two lines in the
handler file
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
why image is not displaying without this code.
how can I resize images into a constant size? and how to have a delete function on it? for deleting the image in the database and not shown in the webpage at runtime. Thanks
ReplyDeleteHello, code appears to be working, but i'm not seeing the image in the gridview, only a red x. Whad do you suppose might be causing this?
ReplyDeletedo we have to insert images in the Image2 field also same as we inserted in Image field?
ReplyDeletenice code
ReplyDeletethank you for the coding. It works.
ReplyDeleteHi,,
ReplyDeleteArgumentOutofRange Exception was unhandled by usercode...
"Specified argument was out of the range of valid values.
Parameter name: offset"
Am getting the error like this.... Some pictures are displaying in the Datalist (Instead of GridView am using Datalist).
And the browser side..Showing (4 itms remiaing...Downloading picture http://localhost:1213/PL/imgHandler.ashx...
Please help me on this issue...
Can You help me code same : http://thegioididong.com/sieu-thi-dien-thoai-di-dong%2Ctrang-chu-42.aspx
ReplyDeletehelp me !
I need it ! when I move mouse to pictures which show infomations about that pictures !
all is f9 but image is not displayed
ReplyDeleteHi,
ReplyDeleteI have Error in the Default.aspx.cs page at this line:
int result = cmd.ExecuteNonQuery();
Error:
Cannot insert the value NULL into column 'ID', table 'MadinaEdu.dbo.Images'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Also after running the application no any data inserted in my DB.
Please guide me
Hi,
ReplyDeleteI have error in the Default.aspx.cs page at Line:
int result = cmd.ExecuteNonQuery();
Error:
Cannot insert the value NULL into column 'ID', table 'MadinaEdu.dbo.Images'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Can you Please Help me/
Did anyone ever get this to work? I have done the code for the upload image to sql and the display image in datagrid and all I get are red x's no images show up?
ReplyDeleteuu
ReplyDeletehey amit i m getting some problem retriveing image from database,while retriving image i m getting same image again n again but imageid is different.please help.....
ReplyDeletecan u help me to store the path in database,please specify the datatype of the field in the database table
ReplyDeleteilike ur coding
ReplyDeleteUr code is very helpful but image is not showing in gridveiw inspite of taking image control in gridveiw html page...it shows like there is no image in database..
ReplyDeleteplease help
@Shuvankar Nandy : Can you provide me details or the code u r using with database so that i can look into it
ReplyDeleteHello, I am having trouble with the ASP version of the code. Any help is much appreciated.
ReplyDeletePublic Class Handler
Implements IHttpHandler --> GETTING AN ERROR HERE ON the Handler says "
class handler must implement read only property is resuable as Boolean for
system.web.IHTTPhandler..."
Public Sub ProcessRequest(ByVal context As HttpContext)
Dim con As New SqlConnection()
con.ConnectionString =
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select ImageName,Image from Images" +
" where ID =@IID"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ImageID As New SqlParameter
("@IID", System.Data.SqlDbType.Int)
ImageID.Value = context.Request.QueryString("ID")
cmd.Parameters.Add(ImageID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("Image"), Byte()))
dReader.Close()
con.Close()
End Sub
End Class
thanks,
Sandy
@Sandy : Add this code in your code bihind file of handler class in bottom
ReplyDeletePublic ReadOnly Property IsReusable()
As Boolean _
Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
This should fix your error
Nice One :-)
ReplyDeleteThanks for the help
ReplyDeleteHi Jain,
ReplyDeleteI got clear idea about ,how do get a image in gird view...
Preview
ReplyDeleteEdit
Ritu said...
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New MySqlConnection()
con.ConnectionString = "server=xxxx;User Id=xxxx;Password=xxxx;database=xxxx;Persist Security Info=True"
Dim cmd As New MySqlCommand()
cmd.CommandText = "SELECT * FROM images WHERE imgid=@ID"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ImageID As New MySqlParameter("@ID", MySqlDbType.Int32)
ImageID.Value = context.Request.QueryString("imgid")
cmd.Parameters.Add(ImageID)
con.Open()
Dim dReader As MySqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("img"), Byte()))
dReader.Close()
con.Close()
End Sub
--------------------------
The dReader can't seem to be able to read parameter ImageID or ID(?). No rows are returned.
I need help w/ this.
July 28, 2011 12:34 PM
Add profile picture
Word verification
@Ritu : Do u have image stored in your database ?
ReplyDeleteYup, i already have images stored on my database
ReplyDeleteMy table named, 'images', contains 3 fields namely
imgid(int, Primary key), caption(varchar), and
img(BLOB)
Additional Info:
ReplyDeleteWhen I replace the query
from:
SELECT * FROM images WHERE imgid=@ID
to a valid imgid from my database
SELECT * FROM images WHERE imgid='13'
- the image is shown. That's why I know that the problem is with the parameter @ID
Update:
ReplyDeleteProblem Solved!!
I knew what the problem was ---
ImageID.Value = context.Request.QueryString("imgid")
<-- I changed the "ID" into "imgid", I misunderstood it. My bad.
when I used this, It worked !!:
context.Request.QueryString("ID")
Whew ~ I'm really new at this. Thanks for helping(with the code) and trying to help(with my code problem), dude =)
@Ritu : Good to know your problem is solved :)) keep visiting
ReplyDeleteThanks again ~
ReplyDeleteHey,
ReplyDeleteI also have a small problem with the code. Everything works fine, I can render the images. But sometimes when i refresh it cant fetch all the images from the database and their image fields are empty. And browser (chrome, firefox) status is "Waiting for localhost". For firefox situation is worse, even if it successfully fetches all images it is still stuck at waiting status.
How can I fix this one? I dont want the browser constantly remain at waiting for connection status when page is visited.
@guen : this seems to be a problem with browser's cache, u can try setting no cache in page directive or setting expire headers for the images in ur aspx page
ReplyDeletehello sir,
ReplyDeleteThis is the problem i have faced with my coding please help me
"The parameterized query '(@ID int)Select ImageName,Image from Images where ID =@ID' expects the parameter '@ID', which was not supplied."
and this code is i have used
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings
["const"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ImageName,Image from Images" +
" where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter
("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}
public bool IsReusable {
get {
return false;
}
}
}
Hi its me again,
ReplyDeleteI have error in the Default.aspx.cs page at Line:
int result = cmd.ExecuteNonQuery();
Error:
Cannot insert the value NULL into column 'ID', table 'latha.dbo.priya'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Can you Please Help me
This post is not at all working. :(
ReplyDelete@Alan J: What error/problem you are facing ?
ReplyDeletehello every one. please can someone help me with this error please lorinmanco@gmail.com
ReplyDeleteError 1 Literal content ('') is not allowed within a 'System.Web.UI.WebControls.DataControlFieldCollection'
Amit, thanks a lot for posting code to help newbies like me - when I try to use your code on vb 2008 express edition some of it wants to update from previous version when this occurs I cant open it am I being extremely stupid? in what /i am doing? only previous experience of vb was using it like a notepad to build a quiz showing 4 possible answers if hte user answered correctly it added 1 to the score and if answered incorectly took a life away so you will see I am real newbie - my email is fizzsdesigns@aol.com
ReplyDeleteHI amit
ReplyDeleteThere is a problem with gridview not displaying images. Not even cross symbols. I had test queried in my database where i could find my images but its not displayed in gridview. One more funny thing is there are no errors displayed neither warnings. Plz help me soon
Hiya, pleasant blog site develop,great write-up and i believe that you're right :)
ReplyDeletehii friends please help me..
ReplyDeletethe code is wrking.. and images are uploded to database.. bt the image is not appear in the browser..it shows system.byte{}
how to write the mouse click event to grid view images.
ReplyDeletei want to display the gridview image in a separate page when i clicked on that image
Hi Can u Plz Explain what is Handler
ReplyDeletenice
ReplyDeletehai....
ReplyDeletei try to upload large and small size of picture ..
when i display the picture the the size not same...
how to display image in same size...?
@Above: You can resize images before uploading to database
ReplyDeleteTHANK YOU SO MUCH !! i've been searching for working tutorial for ages ! It works like a charm !
ReplyDeleteI downloaded the version where a parameter is passed to view an image with a specific ID, but
i'm facing a problem with this line of code
Dim dReader As SqlDataReader =cmd.ExecuteReader()
it keeps giving me this error "Failed to convert parameter value from a String to a Int32."
what could be the problem and how can i fix it?
@dancinqueen89: Plz try converting ID parameter to int32 as
ReplyDeleteDim ImageID As New SqlParameter("@ID", System.Data.SqlDbType.Int)
ImageID.Value = Convert.ToInt32(Context.Request.QueryString("ID"))
THANK YOU SO MUCH !! i've been searching for working tutorial for ages .
ReplyDeletebut whenever i am uploading data ,it is going to upload two times.
can u tell me the command to create the table as in your example.
The name 'context' doesnt exists in the current context.
ReplyDeletewhy so? :(
@Deovrat A Sharp Spark : Have you added generic handler with below mentioned method ?
ReplyDeletepublic void ProcessRequest (HttpContext context)
Hi Amit, The code you provided is working fine. The only problem is that on my website i do not see the actual image only an icon X is diplayed in datagrid view. Any help would be apreciated.
ReplyDelete@Above: please check your image path in html source of gridview, also check whether image data is received from database
ReplyDeleteThanks Amit
ReplyDeleteThis one very useful example to develop a project
ReplyDelete