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