Display Images In GridView From DataBase Asp.Net

In this example i am explaining how to Show Display Images In GridView From DataBase In ASP.NET Using C# And VB.NET or showing images stored or saved in SQL Server database in gridview,For this i've already stored images in Database.

Table schema is shown below, ID column is primary key with Identity increment,datatype of Image column is Binary.

Display Images In GridView From DataBase Asp.Net
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
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

121 comments:

  1. Your Post is not visible...

    I Need your help for My blog..can u give me your email address so I tell you my problem...

    regards

    ReplyDelete
  2. your tutorial is too much helpful...thnks a lot...
    but 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 ....

    ReplyDelete
  3. @GORA..........ROCK THE WORLD:

    I 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

    ReplyDelete
  4. thanks a lot ....amit...
    actually i just miss the single line of code...
    gridview.databind();
    thats why not getting the desired output...
    thanks again

    ReplyDelete
  5. at handler.ashx, error message on

    "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!

    ReplyDelete
  6. @Anonymous , u r not supplying Img_ID in ur query ,

    Please post full code of handler.ashx with select command so that i can look into or full

    ReplyDelete
  7. This comment has been removed by a blog administrator.

    ReplyDelete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. Hi Amit,

    With 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. :)

    ReplyDelete
  10. @edgecrosser:

    You are missing namespaces ,

    Please add these namespaces in code behind

    using Syatem.Data.SqlClient;

    ReplyDelete
  11. Hi Amit,

    Ah yes I forgot the namespaces, thanks!

    ReplyDelete
  12. hi Amit, its me again,

    I 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

    ReplyDelete
  13. Hi Amit,

    I 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 :)

    ReplyDelete
  14. @edgecrosser:

    Please 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

    }

    ReplyDelete
  15. For the InvalidCastException error please make sure that ID field in database is numeric and write exactly same code mention below


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

    ReplyDelete
  16. Hi Amit,

    Sorry for responding late. I will follow your advise and let you know if it worked already. Thanks!

    ReplyDelete
  17. Hi Amit,

    I 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!

    ReplyDelete
  18. Hi Amit,

    It'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.

    ReplyDelete
  19. @edgecrosser

    hi 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

    ReplyDelete
  20. Oh great Amit! I'll try it again and let you know soon :)

    ReplyDelete
  21. Amit it's working now!!! You're a savior! Thank you thank you!!

    ReplyDelete
  22. Hi Amit
    I 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

    ReplyDelete
  23. @Above:

    DOwnload 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 ?

    ReplyDelete
  24. Dear Amit

    Thanks 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

    ReplyDelete
  25. @Above:

    I'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 ?

    ReplyDelete
  26. Hi Amit

    Thanks 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

    ReplyDelete
  27. @wael:

    If 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

    ReplyDelete
  28. hi sir !
    when i implement your coding it run succussfully but image is invisible in the gridview pls help me my mail id--pardeepbeniwal84@gmail.com

    ReplyDelete
  29. @Above:

    you 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

    ReplyDelete
  30. Hi Amit,

    It'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.

    ReplyDelete
  31. @edgecrosser:

    Hi 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

    ReplyDelete
  32. Hi Amit,

    Thanks 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.

    ReplyDelete
  33. Hi Amit,

    Before 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.

    ReplyDelete
  34. 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
  35. ....
    dReader.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

    ReplyDelete
  36. 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

    Thanks again.

    ReplyDelete
  37. hi amit,
    code is working but images are not bind to gridview please help me

    ReplyDelete
  38. Hello Amit,

    Thank 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

    ReplyDelete
  39. Hi Amit,

    I 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 !

    ReplyDelete
  40. Hi..

    It works great !! Thanks a lot

    ReplyDelete
  41. Hi thanks a lot . . .

    ReplyDelete
  42. 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.

    ReplyDelete
  43. hi
    your 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

    ReplyDelete
  44. hi
    thanks 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

    ReplyDelete
  45. Hi,
    Thanks 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

    ReplyDelete
  46. kartiki said...
    " 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"

    ReplyDelete
  47. Hi,
    Thanks 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,

    ReplyDelete
  48. 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

    ReplyDelete
  49. Hi,
    Thank 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

    ReplyDelete
  50. Hi, just want to say thanks for this post, finally it does what I want to do.

    Spent 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

    ReplyDelete
  51. Thanks for the great tutorial. However, I am getting an error when running the VB version: Invalid attempt to read...

    Any help would be appreciated

    ReplyDelete
  52. I tried this code for MYSQL database but didn't work.. can you help me?

    ReplyDelete
  53. hi friends,
    I 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.......

    ReplyDelete
  54. 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!

    ReplyDelete
  55. Hi Amit,

    Cel 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!

    ReplyDelete
  56. Hi Amit,

    Cel 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!

    ReplyDelete
  57. 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 :)

    ReplyDelete
  58. 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 :)

    ReplyDelete
  59. Hi 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.

    Thanks for any help, i'm in a new project again.

    ReplyDelete
  60. Just add this code for vb.net in the handler.ashx after line 28 since it is missing.

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
    Return False
    End Get
    End Property

    ReplyDelete
  61. hi amit
    i 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

    ReplyDelete
  62. I would like to exchange links with your site csharpdotnetfreak.blogspot.com
    Is this possible?

    ReplyDelete
  63. 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:
    <%@ 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

    ReplyDelete
  64. hi your code is workin..
    before 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.

    ReplyDelete
  65. 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

    ReplyDelete
  66. Hello, 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?

    ReplyDelete
  67. do we have to insert images in the Image2 field also same as we inserted in Image field?

    ReplyDelete
  68. thank you for the coding. It works.

    ReplyDelete
  69. Hi,,

    ArgumentOutofRange 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...

    ReplyDelete
  70. Can You help me code same : http://thegioididong.com/sieu-thi-dien-thoai-di-dong%2Ctrang-chu-42.aspx

    help me !
    I need it ! when I move mouse to pictures which show infomations about that pictures !

    ReplyDelete
  71. all is f9 but image is not displayed

    ReplyDelete
  72. Hi,

    I 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

    ReplyDelete
  73. Hi,

    I 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/

    ReplyDelete
  74. 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?

    ReplyDelete
  75. hey 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.....

    ReplyDelete
  76. can u help me to store the path in database,please specify the datatype of the field in the database table

    ReplyDelete
  77. Ur 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..
    please help

    ReplyDelete
  78. @Shuvankar Nandy : Can you provide me details or the code u r using with database so that i can look into it

    ReplyDelete
  79. Hello, I am having trouble with the ASP version of the code. Any help is much appreciated.
    Public 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

    ReplyDelete
  80. @Sandy : Add this code in your code bihind file of handler class in bottom


    Public ReadOnly Property IsReusable()
    As Boolean _

    Implements IHttpHandler.IsReusable
    Get
    Return True
    End Get
    End Property



    This should fix your error

    ReplyDelete
  81. Thanks for the help

    ReplyDelete
  82. Hi Jain,
    I got clear idea about ,how do get a image in gird view...

    ReplyDelete
  83. Preview

    Edit
    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

    ReplyDelete
  84. @Ritu : Do u have image stored in your database ?

    ReplyDelete
  85. Yup, i already have images stored on my database

    My table named, 'images', contains 3 fields namely
    imgid(int, Primary key), caption(varchar), and
    img(BLOB)

    ReplyDelete
  86. Additional Info:
    When 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

    ReplyDelete
  87. Update:
    Problem 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 =)

    ReplyDelete
  88. @Ritu : Good to know your problem is solved :)) keep visiting

    ReplyDelete
  89. Hey,

    I 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.

    ReplyDelete
  90. @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

    ReplyDelete
  91. hello sir,
    This 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;
    }
    }

    }

    ReplyDelete
  92. Hi its me again,

    I 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

    ReplyDelete
  93. This post is not at all working. :(

    ReplyDelete
  94. @Alan J: What error/problem you are facing ?

    ReplyDelete
  95. hello every one. please can someone help me with this error please lorinmanco@gmail.com

    Error 1 Literal content ('') is not allowed within a 'System.Web.UI.WebControls.DataControlFieldCollection'

    ReplyDelete
  96. 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

    ReplyDelete
  97. HI amit
    There 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

    ReplyDelete
  98. Hiya, pleasant blog site develop,great write-up and i believe that you're right :)

    ReplyDelete
  99. hii friends please help me..
    the code is wrking.. and images are uploded to database.. bt the image is not appear in the browser..it shows system.byte{}

    ReplyDelete
  100. how to write the mouse click event to grid view images.
    i want to display the gridview image in a separate page when i clicked on that image

    ReplyDelete
  101. Hi Can u Plz Explain what is Handler

    ReplyDelete
  102. hai....
    i 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...?

    ReplyDelete
  103. THANK YOU SO MUCH !! i've been searching for working tutorial for ages ! It works like a charm !
    I 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?

    ReplyDelete
  104. @dancinqueen89: Plz try converting ID parameter to int32 as

    Dim ImageID As New SqlParameter("@ID", System.Data.SqlDbType.Int)
    ImageID.Value = Convert.ToInt32(Context.Request.QueryString("ID"))

    ReplyDelete
  105. THANK YOU SO MUCH !! i've been searching for working tutorial for ages .
    but 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.

    ReplyDelete
  106. The name 'context' doesnt exists in the current context.

    why so? :(

    ReplyDelete
  107. @Deovrat A Sharp Spark : Have you added generic handler with below mentioned method ?

    public void ProcessRequest (HttpContext context)

    ReplyDelete
  108. 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
  109. @Above: please check your image path in html source of gridview, also check whether image data is received from database

    ReplyDelete
  110. This one very useful example to develop a project

    ReplyDelete