How to Insert Images in Database and How to Retrieve,Bind Images to Gridview using ASP.NET

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
  1. <html xmlns="http://www.w3.org/1999/xhtml" >  
  2. <head runat="server">  
  3. <title>Inserting images into databse and displaying images with gridview</title>  
  4. <style type="text/css">  
  5. .Gridview  
  6. {  
  7. font-family:Verdana;  
  8. font-size:10pt;  
  9. font-weight:normal;  
  10. color:black;  
  11. width:500px;  
  12. }  
  13. </style>  
  14. </head>  
  15. <body>  
  16. <form id="form1" runat="server">  
  17. <div>  
  18. <table>  
  19. <tr>  
  20. <td>  
  21. Image Name:  
  22. </td>  
  23. <td>  
  24. <asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>  
  25. </td>  
  26. </tr>  
  27. <tr>  
  28. <td>  
  29. Upload Image:  
  30. </td>  
  31. <td>  
  32. <asp:FileUpload ID="fileuploadImage" runat="server" />  
  33. </td>  
  34. </tr>  
  35. <tr>  
  36. <td>  
  37. </td>  
  38. <td>  
  39. <asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />  
  40. </td>  
  41. </tr>  
  42. </table>  
  43. </div>  
  44. <div>  
  45. <asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"  
  46. HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">  
  47. <Columns>  
  48. <asp:BoundField HeaderText = "Image Name" DataField="imagename" />  
  49. <asp:TemplateField HeaderText="Image">  
  50. <ItemTemplate>  
  51. <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>  
  52. </ItemTemplate>  
  53. </asp:TemplateField>  
  54. </Columns>  
  55. </asp:GridView>  
  56. </div>  
  57. </form>  
  58. </body>  
  59. </html>  
After that add using System.IO; using System.Data.SqlClient; and using System.Configuration;namespaces and write the following code in code behind
  1. string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;    
  2.     protected void Page_Load(object sender, EventArgs e)    
  3.     {    
  4.         if (!IsPostBack)    
  5.         {    
  6.         BindGridData();    
  7.         }    
  8.     }    
  9. /// <summary>    
  10. /// btnUpload_Click event is used to upload images into database    
  11. /// </summary>    
  12. /// <param name="sender"></param>    
  13. /// <param name="e"></param>    
  14. protected void btnUpload_Click(object sender, EventArgs e)    
  15.     {    
  16. //Condition to check if the file uploaded or not    
  17.         if (fileuploadImage.HasFile)    
  18.             {    
  19. //getting length of uploaded file    
  20.     int length = fileuploadImage.PostedFile.ContentLength;    
  21. //create a byte array to store the binary image data    
  22. byte[] imgbyte = new byte[length];    
  23. //store the currently selected file in memeory    
  24. HttpPostedFile img = fileuploadImage.PostedFile;    
  25. //set the binary data    
  26. img.InputStream.Read(imgbyte, 0, length);    
  27. string imagename = txtImageName.Text;    
  28. //use the web.config to store the connection string    
  29. SqlConnection connection = new SqlConnection(strcon);    
  30. connection.Open();    
  31. SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (@imagename,@imagedata)", connection);    
  32. cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imagename;    
  33. cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;    
  34. int count = cmd.ExecuteNonQuery();    
  35. connection.Close();    
  36. if (count == 1)    
  37.         {    
  38.         BindGridData();    
  39.         txtImageName.Text = string.Empty;    
  40.         ScriptManager.RegisterStartupScript(thisthis.GetType(), "alertmessage""javascript:alert('" + imagename + " image inserted successfully')"true);    
  41.         }    
  42. }    
  43. }    
  44. /// <summary>    
  45. /// function is used to bind gridview    
  46. /// </summary>    
  47. private void BindGridData()    
  48. {    
  49.    SqlConnection connection = new SqlConnection(strcon);    
  50.    SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);    
  51.    SqlDataAdapter daimages = new SqlDataAdapter(command);    
  52.    DataTable dt = new DataTable();    
  53.    daimages.Fill(dt);    
  54.    gvImages.DataSource = dt;    
  55.    gvImages.DataBind();    
  56.    gvImaes.Attributes.Add("bordercolor""black");    
  57. }    
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
  1. string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();  
  2. public void ProcessRequest(HttpContext context)  
  3. {  
  4. string imageid = context.Request.QueryString["ImID"];  
  5. SqlConnection connection = new SqlConnection(strcon);  
  6. connection.Open();  
  7. SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);  
  8. SqlDataReader dr = command.ExecuteReader();  
  9. dr.Read();  
  10. context.Response.BinaryWrite((Byte[])dr[0]);  
  11. connection.Close();  
  12. context.Response.End();  
  13. }  
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
  1. <connectionStrings>  
  2. <add name="dbconnection" connectionString="Data Source=sa;Integrated Security=true;Initial Catalog=admin"/>  
  3. </connectionStrings>