In this example we will store employee information with an employee image preview and display the inserted employee information with PhotoID in GridView.

Now to start this example step-by-step.

Step 1

This is the database side.

First create an EmployeeImage table in the SQL database as in the following.

  1. create Table EmployeeImage
  2. (
  3. ImageId int identity(1,1), --- make auto increment id
  4. ImgName nvarchar(50),
  5. Photo image,
  6. Contact nvarchar(15),
  7. Designation varchar(50)
  8. )
Step 2

Go to Visual Studio.

Step 3

This is the Page Design.

Here open your project and add a new .aspx page as in the following.

Now right-click on your project name and add a new item to the project.

Add New Item
Figure 1: Add New Item

Click on new item and add a new webform and provide a suitable name as follows:
Add Design Page
Figure 2: Add Design Page

First write the image upload and display the preview code using the jQuery function as in the following:
  1. <script type="text/javascript">
  2. function previewFile() {
  3. var ImagePreview = document.querySelector('#<%=ImgUpload.ClientID %>');
  4. var ImageFile = document.querySelector('#<%=FileUpload.ClientID %>').files[0];
  5. var reader = new FileReader();
  6. reader.onloadend = function () {
  7. ImagePreview.src = reader.result;
  8. }
  9. if (ImageFile) {
  10. reader.readAsDataURL(ImageFile);
  11. } else {
  12. ImagePreview.src = "";
  13. }
  14. }
  15. </script>
Second write the design code for the employee information insert screen as follows:
  1. <div>
  2. <fieldset style="width: 490px"><legend>Employee Information With PhotoID</legend>
  3. <asp:Table runat="server" Width="442px" >
  4. <asp:TableRow>
  5. <asp:TableCell></asp:TableCell><asp:TableCell><asp:Image ID="ImgUpload" ToolTip="Upload Employee Photo Here" runat="server" Height="200px" Width="200px" /></asp:TableCell>
  6. </asp:TableRow>
  7. <asp:TableRow>
  8. <asp:TableCell> Upload Image:</asp:TableCell><asp:TableCell> <input ID="FileUpload" type="file" name="file" onchange="previewFile()" runat="server" /></asp:TableCell>
  9. </asp:TableRow>
  10. <asp:TableRow>
  11. <asp:TableCell>Employee Name:</asp:TableCell><asp:TableCell><asp:TextBox ID="txtName" runat="server"></asp:TextBox> </asp:TableCell>
  12. </asp:TableRow>
  13. <asp:TableRow>
  14. <asp:TableCell>Contact</asp:TableCell><asp:TableCell><asp:TextBox ID="txtContact" runat="server" ></asp:TextBox></asp:TableCell>
  15. </asp:TableRow>
  16. <asp:TableRow>
  17. <asp:TableCell>Designation</asp:TableCell><asp:TableCell><asp:TextBox ID="txtDesignation" runat="server" ></asp:TextBox></asp:TableCell>
  18. </asp:TableRow>
  19. <asp:TableRow>
  20. <asp:TableCell></asp:TableCell><asp:TableCell><asp:Button ID="btnDataInsert" runat="server" Text="SUBMIT" onclick="btnDataInsert_Click" /></asp:TableCell>
  21. </asp:TableRow>
  22. </asp:Table>
  23. </fieldset>
  24. </div>
Add a GridView to display the employee information with the employee's PhotoID.
  1. <div>
  2. <asp:GridView ID="GridEmpImg" runat="server" AutoGenerateColumns="False">
  3. <Columns>
  4. <asp:TemplateField HeaderText="Image">
  5. <ItemTemplate>
  6. <asp:Image ID="Image1" runat="server" ImageUrl='<%# "DisplayImage.ashx?ImageId="+ Eval("ImageId") %>' Height="150px" Width="150px"/>
  7. </ItemTemplate>
  8. </asp:TemplateField>
  9. <asp:BoundField HeaderText = "Employee Name" DataField="imgname" />
  10. <asp:BoundField HeaderText = "Contact" DataField="Contact" />
  11. <asp:BoundField HeaderText = "Designation" DataField="Designation" />
  12. </Columns>
  13. </asp:GridView>
  14. </div>
Finally our design for the preceding code will be as follows:

UI Design
Figure 3: UI Design

Step 4

Add a Connection String in the web.config file as in the following:
  1. <connectionStrings>
  2. <add name="connstr" connectionString="Data Source=RAKESH-PC;Initial Catalog=SqlServerTech;User ID=sa;Password=jm" providerName="System.Data.SqlClient"/>
  3. <add name="Pratical_testConnectionString" connectionString="Data Source=RAKESH-PC;Initial Catalog=Pratical_test;User ID=sa" providerName="System.Data.SqlClient"/>
  4. </connectionStrings>
Step 5

This is the Page code.

In this section we will write the image upload code, insert code and select employee information with PhotoId code using a generic file method HttpHandler as follows:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Configuration;
  8. using System.Data.SqlClient;
  9. using System.Data;
  10. using System.IO;
  11. namespace Test_WebApplication.ImageCode
  12. {
  13. public partial class ImageDemo : System.Web.UI.Page
  14. {
  15. string constring = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
  16. protected void Page_Load(object sender, EventArgs e)
  17. {
  18. EmpImageInfo();
  19. }
  20. protected void Upload(object sender, EventArgs e)
  21. {
  22. string fileName = FileUpload.PostedFile.FileName;
  23. }
  24. protected void btnDataInsert_Click(object sender, EventArgs e)
  25. {
  26. int length = FileUpload.PostedFile.ContentLength;
  27. byte[] imgbyte = new byte[length];
  28. HttpPostedFile image = FileUpload.PostedFile;
  29. image.InputStream.Read(imgbyte, 0, length);
  30. string ImgName = txtName.Text;
  31. string Contact = txtContact.Text;
  32. string Designation = txtDesignation.Text;
  33. SqlConnection conn = new SqlConnection(constring);
  34. conn.Open();
  35. SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeImage (ImgName,photo,Contact,Designation) VALUES (@ImgName,@photo,@Contact,@Designation)", conn);
  36. cmd.Parameters.Add("@ImgName", SqlDbType.VarChar, 50).Value = ImgName;
  37. cmd.Parameters.Add("@photo", SqlDbType.Image).Value = imgbyte;
  38. cmd.Parameters.Add("@Contact", SqlDbType.NVarChar, 15).Value = Contact;
  39. cmd.Parameters.Add("@Designation", SqlDbType.VarChar, 50).Value = Designation;
  40. int count = cmd.ExecuteNonQuery();
  41. conn.Close();
  42. if (count == 1)
  43. {
  44. EmpImageInfo();
  45. ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + ImgName + " PhotoID Information Inserted successfully')", true);
  46. }
  47. txtName.Text = string.Empty;
  48. txtContact.Text = string.Empty;
  49. txtDesignation.Text = string.Empty;
  50. }
  51. private void EmpImageInfo()
  52. {
  53. SqlConnection conn = new SqlConnection(constring);
  54. SqlCommand cmd = new SqlCommand("SELECT ImageId, ImgName,Photo,Contact,Designation from EmployeeImage", conn);
  55. SqlDataAdapter da = new SqlDataAdapter(cmd);
  56. DataTable dt = new DataTable();
  57. da.Fill(dt);
  58. GridEmpImg.DataSource = dt;
  59. GridEmpImg.DataBind();
  60. }
  61. }
  62. }
Step 6

Add a .ashx.cs file to the project.

Now add one more important file, a generic handler, to the project for the image display in the GridView as follows:

Add Generic File
Figure 4: Add Generic File

Now write the generic handler code to display the image from the database as in the following:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Configuration;
  6. using System.Data.SqlClient;
  7. using System.IO;
  8. using System.Data;
  9. namespace Test_WebApplication.ImageCode
  10. {
  11. public class DisplayImage : IHttpHandler
  12. {
  13. string constring = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
  14. public void ProcessRequest(HttpContext context)
  15. {
  16. string ImageId = context.Request.QueryString["ImageId"];
  17. SqlConnection conn = new SqlConnection(constring);
  18. conn.Open();
  19. SqlCommand cmd = new SqlCommand("select Photo from EmployeeImage where ImageId=" + ImageId, conn);
  20. SqlDataReader dr = cmd.ExecuteReader();
  21. dr.Read();
  22. context.Response.BinaryWrite((Byte[])dr[0]);
  23. conn.Close();
  24. context.Response.End();
  25. }
  26. public bool IsReusable
  27. {
  28. get
  29. {
  30. return false;
  31. }
  32. }
  33. }
  34. }
Step 7

Run the code in a browser by pressing F5.

UI on Browser
Figure 5: UI on Browser

Choose an image file from disk.

Choose file from disk
Figure 6: Choose file from disk

Showing the image preview as follows:

Image Preview
Figure 7: Image Preview

Now click the submit button and you will get a record insert message in a dialog box as in the following:

Message Display
Figure 8: Message Display

The inserted employee record is shown in the GridView control.

Inserted Record Display
Figure 9: Inserted Record Display

Also check in the database table as in the following:

Data Store Database
Figure 10:

In the preceding figure you can see that the image was stored in binary data format.