Upload Image To Database and Show in ASP.Net GridView

This article shows how to upload a photo image with other details in an ASP.NET and C# application and display the details in a GridView. This is a simple web application for beginners to learn C#, ASP.NET and .Net controls. This will show how to upload and retrieve an image with other information from a database and display it in a GridView.

The following sample demonstrates step-by-step.

  1. Create a table in a database with the following fields:
    database Table
  2. In Visual Studio select "File" -> "New" -> "Project..." as in the following:
    Projects
  3. Create a project and an ASP.NET WebApplication named ImageUploadInDB as below:
    WebApplication
  4. Open the default.aspx and modify the code as below:
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ImageUploadInDB._Default" %>  
    2.   
    3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    4. <html xmlns="http://www.w3.org/1999/xhtml">  
    5. <head runat="server">  
    6.     <title></title>  
    7. </head>  
    8. <body>  
    9.     <form id="form1" runat="server">  
    10.     <div>  
    11.         <table>  
    12.             <tr>  
    13.                 <td colspan="2">  
    14.                     <h2>Employee Details</h2>  
    15.                 </td>  
    16.             </tr>  
    17.             <tr>  
    18.                 <td>ID</td>  
    19.                 <td><asp:TextBox ID="txtID" runat="server" Width="211px"></asp:TextBox></td>  
    20.             </tr>  
    21.             <tr>  
    22.                 <td>Name</td>  
    23.                 <td><asp:TextBox ID="txtName" runat="server" Width="211px"></asp:TextBox></td>  
    24.             </tr>  
    25.             <tr>  
    26.                 <td>BloodGroup</td>  
    27.                 <td><asp:TextBox ID="txtBloodGroup" runat="server" Width="211px"></asp:TextBox></td>  
    28.             </tr>  
    29.             <tr>  
    30.                 <td>Emergency Contact No.</td>  
    31.                 <td><asp:TextBox ID="txtContactNo" runat="server" Width="211px"></asp:TextBox></td>  
    32.             </tr>  
    33.             <tr>  
    34.                 <td>Photo:</td>  
    35.                 <td><asp:FileUpload ID="fileuploadEmpImage" runat="server" Width="180px" /></td>  
    36.             </tr>  
    37.             <tr>  
    38.                 <td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" /></td>  
    39.             </tr>  
    40.         </table>  
    41.     </div>  
    42.     <div>  
    43.         <asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">  
    44.             <Columns>  
    45.              <asp:BoundField HeaderText="Name" DataField="Name" />  
    46.               <asp:BoundField HeaderText="Blood Group" DataField="BloodGroup" />  
    47.               <asp:BoundField HeaderText="Phone No" DataField="PhoneNo" />  
    48.                 <asp:BoundField HeaderText="Image" DataField="Image" Visible="false" />  
    49.                 <asp:TemplateField HeaderText="Image">  
    50.                     <ItemTemplate>  
    51.                         <asp:Image ID="Image1" runat="server" ImageUrl='<%# "EmployeeImageHandler.ashx?Id="+ Eval("Id") %>'  
    52.                             Height="150px" Width="150px" />  
    53.                     </ItemTemplate>  
    54.                 </asp:TemplateField>  
    55.             </Columns>  
    56.         </asp:GridView>  
    57.     </div>  
    58.     </form>  
    59. </body>  
    60. </html> 
  5. Open the Default.aspx.cs and modify the code as below:
    1. using System;  
    2. using System.Web;  
    3. using System.Web.UI;  
    4. using System.Data.SqlClient;  
    5. using System.Data;  
    6.   
    7. namespace ImageUploadInDB  
    8. {  
    9.     public partial class _Default : System.Web.UI.Page  
    10.     {  
    11.         protected void Page_Load(object sender, EventArgs e)  
    12.         {  
    13.             if (!Page.IsPostBack)  
    14.             {  
    15.                 BindGridData();  
    16.             }   
    17.         }   
    18.         protected void btnSubmit_Click(object sender, EventArgs e)  
    19.         {  
    20.             //Condition to check if the file uploaded or not   
    21.             if (fileuploadEmpImage.HasFile)  
    22.             {  
    23.                 //getting length of uploaded file  
    24.                 int length = fileuploadEmpImage.PostedFile.ContentLength;  
    25.                 //create a byte array to store the binary image data  
    26.                 byte[] imgbyte = new byte[length];  
    27.                 //store the currently selected file in memeory  
    28.                 HttpPostedFile img = fileuploadEmpImage.PostedFile;  
    29.                 //set the binary data  
    30.                 img.InputStream.Read(imgbyte, 0, length);  
    31.                 int id = Convert.ToInt32(txtID.Text);  
    32.                 string name = txtName.Text;  
    33.                 string bloodGroup = txtBloodGroup.Text;  
    34.                 string phoneNo = txtContactNo.Text;  
    35.   
    36.                 //Connection String  
    37.                 SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=CMS;Integrated Security=True");  
    38.                 //Open The Connection  
    39.                 connection.Open();  
    40.                 SqlCommand cmd = new SqlCommand("INSERT INTO Employee (Id,Name,BloodGroup,PhoneNo,Image) VALUES (@id,@Name,@BloodGroup,@ContactNo,@imagedata)", connection);  
    41.                 cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;  
    42.                 cmd.Parameters.Add("@Name", SqlDbType.VarChar,150).Value = name;  
    43.                 cmd.Parameters.Add("@BloodGroup", SqlDbType.NVarChar, 250).Value = bloodGroup;  
    44.                 cmd.Parameters.Add("@ContactNo", SqlDbType.VarChar, 50).Value = phoneNo;  
    45.                 cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;  
    46.   
    47.                 int count = cmd.ExecuteNonQuery();  
    48.                 //Close The Connection  
    49.                 connection.Close();  
    50.                 if (count == 1)  
    51.                 {  
    52.                     //BindGridData();  
    53.                     txtID.Text = string.Empty;  
    54.                     txtName.Text = string.Empty;  
    55.                     txtBloodGroup.Text = string.Empty;  
    56.                     txtContactNo.Text = string.Empty;  
    57.                     ScriptManager.RegisterStartupScript(thisthis.GetType(), "alertmessage""javascript:alert('Record added successfully')"true);  
    58.                     //call the method to bind the grid  
    59.                     BindGridData();  
    60.                 }  
    61.             }   
    62.         }  
    63.   
    64.         private void BindGridData()  
    65.         {  
    66.             SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=CMS;Integrated Security=True");  
    67.             SqlCommand command = new SqlCommand("SELECT Id,Name,BloodGroup,PhoneNo,Image from [Employee]", connection);  
    68.             SqlDataAdapter daimages = new SqlDataAdapter(command);  
    69.             DataTable dt = new DataTable();  
    70.             daimages.Fill(dt);  
    71.             grdEmployee.DataSource = dt;  
    72.             grdEmployee.DataBind();  
    73.         }         
    74.   
    75.     }  
  6. Add a new file in solution
    new file in solution
  7. Add the Generic Handler and name it EmployeeImageHandler.ashx.
    Generic Handler
  8. Modify the code of the Generic Handler class as below:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Data.SqlClient;  
    6.   
    7. namespace ImageUploadInDB  
    8. {  
    9.     /// <summary>  
    10.     /// Summary description for EmployeeImageHandler  
    11.     /// </summary>  
    12.     public class EmployeeImageHandler : IHttpHandler  
    13.     {  
    14.   
    15.         public void ProcessRequest(HttpContext context)  
    16.         {  
    17.             string imageid = context.Request.QueryString["Id"];  
    18.             SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=CMS;Integrated Security=True");  
    19.             connection.Open();  
    20.             SqlCommand command = new SqlCommand("select Image from Employee where Id=" + imageid, connection);  
    21.             SqlDataReader dr = command.ExecuteReader();  
    22.             dr.Read();  
    23.             context.Response.BinaryWrite((Byte[])dr[0]);  
    24.             connection.Close();  
    25.             context.Response.End();  
    26.         }  
    27.   
    28.         public bool IsReusable  
    29.         {  
    30.             get  
    31.             {  
    32.                 return false;  
    33.             }  
    34.         }  
    35.     }  
  9. Run the code, the page will be opened as below:
    Run the code
  10. Make an entry in all fields and add an image as below:
    add image
  11. Click the Save button, a message will be prompt and the record wil be saved and shown in the GridView as below
    record saved
Conclusion

In this article I explained step-by-step how to upload an image with other details to a database and show the image in a GridView.

Up Next
    Ebook Download
    View all
    Learn
    View all