Binding Image With GridView And Updating Image In GridView

This article shows how to bind data in GridView controls using database and to bind controls with a database. I will also show you how to handle GridView common events in this. Here I’ve described events such as Edit Update and Delete event.

Also, it displays Image uploading and binding in GridView and then updating image in GridView.

Also read

Initial Chamber

Step 1: Open Visual Studio and create an empty website, then provide a suitable name GridViewImageUploading.

Step 2: In Solution Explorer you will get your empty website, then add some web forms.

GridViewImageUploading (your empty website). Right click and select Add New Item Web Form. Name it GridViewImageUploading.aspx.

For SQL Server database

Create a database in SQL server and named it SchoolDB (You can give your own name)

Database Chamber

Step 3: In SchoolDB create a table named Product.

Here's the query

  1. USE [SchoolDB]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Image_Details]    Script Date: 07.09.2015 4:34:24 PM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[Image_Details](  
  15.     [ImageId] [int] IDENTITY(1,1) NOT NULL,  
  16.     [ImageName] [varchar](50) NULL,  
  17.     [Image] [nvarchar](maxNULL  
  18. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  19.   
  20. GO  
  21.   
  22. SET ANSI_PADDING OFF  
  23. GO  
Table Product structure is here

Table Product structure
                                             Figure 1

After query execution

After query execution
                                                                           Figure 2

Design Chamber

Step 4: Open the GridViewImageUploading.aspx file and write some code for the design of the application.

Step 4.1: Put stylesheet code in head chamber of page.

Set your style of page according to your need of design.

Step 4.2: Choose control from toolbox and put on your design page as in the following code snippet:
  1. <h3 style="color: #0000FF; font-style: italic">Display Image and update, delete in GridView Using ASP.NET</h3>  
  2. <div>  
  3.     <asp:FileUpload ID="fileupload" runat="server" />  
  4.     <asp:Button ID="upload" runat="server" Font-Bold="true" Text="Upload" OnClick="upload_Click" />  
  5. <asp:Label ID="lblResult" runat="server"/>


  6.     <br />  
  7.     <br />  
  8. </div>  
  9. <div>  
  10.     <asp:GridView runat="server" ID="gvImage" AutoGenerateColumns="false" AllowPaging="True" OnRowCancelingEdit="gvImage_RowCancelingEdit" DataKeyNames="ImageId" CellPadding="4" OnRowEditing="gvImage_RowEditing" OnRowUpdating="gvImage_RowUpdating" OnRowDeleting="gvImage_RowDeleting" HeaderStyle-BackColor="Tomato">  
  11.         <Columns>  
  12.             <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px">  
  13.                 <ItemTemplate>  
  14.                     <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>  
  15.                 </ItemTemplate>  
  16.             </asp:TemplateField>  
  17.             <asp:TemplateField HeaderText="Name" HeaderStyle-Width="200px">  
  18.                 <ItemTemplate>  
  19.                     <asp:Label ID="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>  
  20.                 </ItemTemplate>  
  21.                 <EditItemTemplate>  
  22.                     <asp:TextBox ID="txt_Name" runat="server" Text='<%# Eval("ImageName") %>'></asp:TextBox>  
  23.                 </EditItemTemplate>  
  24.             </asp:TemplateField>  
  25.             <asp:TemplateField HeaderText="Image" HeaderStyle-Width="200px">  
  26.                 <ItemTemplate>  
  27.                     <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>' Height="80px" Width="100px" />  
  28.                 </ItemTemplate>  
  29.                 <EditItemTemplate>  
  30.                     <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("Image") %>' Height="80px" Width="100px" />  
  31.                     <br />  
  32.                     <asp:FileUpload ID="FileUpload1" runat="server" />  
  33.                 </EditItemTemplate>  
  34.             </asp:TemplateField>  
  35.             <asp:TemplateField HeaderStyle-Width="150px">  
  36.                 <ItemTemplate>  
  37.                     <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>  
  38.                     <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton>  
  39.                 </ItemTemplate>  
  40.                 <EditItemTemplate>  
  41.                     <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>  
  42.                     <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>  
  43.                 </EditItemTemplate>  
  44.             </asp:TemplateField>  
  45.         </Columns>  
  46.     </asp:GridView>  
  47. </div>  
Design of page looks like the following:

Design of page
                                                                                 Figure 3

Here I've designed the GridView Control and used some property as in the following code snippet:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewImageUploading.aspx.cs" Inherits="GridViewImageUploading" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>An article by Upendra Pratap Shahi</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.         <h3 style="color: #0000FF; font-style: italic">Display Image and update, delete in GridView Using ASP.NET</h3>  
  12.         <div>  
  13.             <asp:FileUpload ID="fileupload" runat="server" />  
  14.             <asp:Button ID="upload" runat="server" Font-Bold="true" Text="Upload" OnClick="upload_Click" />  
  15. <asp:Label ID="lblResult" runat="server"/>


  16.             <br />  
  17.             <br />  
  18.         </div>  
  19.         <div>  
  20.             <asp:GridView runat="server" ID="gvImage" AutoGenerateColumns="false" AllowPaging="True"  
  21.                 OnRowCancelingEdit="gvImage_RowCancelingEdit" DataKeyNames="ImageId" CellPadding="4"  
  22.                 OnRowEditing="gvImage_RowEditing" OnRowUpdating="gvImage_RowUpdating" OnRowDeleting="gvImage_RowDeleting" HeaderStyle-BackColor="Tomato">  
  23.                 <Columns>  
  24.                     <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px">  
  25.                         <ItemTemplate>  
  26.                             <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>  
  27.                         </ItemTemplate>  
  28.                     </asp:TemplateField>  
  29.                     <asp:TemplateField HeaderText="Name" HeaderStyle-Width="200px">  
  30.                         <ItemTemplate>  
  31.                             <asp:Label ID="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>  
  32.                         </ItemTemplate>  
  33.                         <EditItemTemplate>  
  34.                             <asp:TextBox ID="txt_Name" runat="server" Text='<%# Eval("ImageName") %>'></asp:TextBox>  
  35.                         </EditItemTemplate>  
  36.                     </asp:TemplateField>  
  37.                     <asp:TemplateField HeaderText="Image" HeaderStyle-Width="200px">  
  38.                         <ItemTemplate>  
  39.                             <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>'  
  40.                                 Height="80px" Width="100px" />  
  41.                         </ItemTemplate>  
  42.                         <EditItemTemplate>  
  43.                             <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("Image") %>'  
  44.                                 Height="80px" Width="100px" /><br />  
  45.                             <asp:FileUpload ID="FileUpload1" runat="server" />  
  46.                         </EditItemTemplate>  
  47.                     </asp:TemplateField>  
  48.                     <asp:TemplateField HeaderStyle-Width="150px">  
  49.                         <ItemTemplate>  
  50.                             <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>  
  51.                             <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton>  
  52.                         </ItemTemplate>  
  53.                         <EditItemTemplate>  
  54.                             <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>  
  55.                             <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>  
  56.                         </EditItemTemplate>  
  57.                     </asp:TemplateField>  
  58.                 </Columns>  
  59.             </asp:GridView>  
  60.         </div>  
  61.     </form>  
  62. </body>  
  63. </html>  
Your design looks like following figure:

design
                                                                        Figure 4
Configure Chamber

Add the following code in Web.configure.
  1. <connectionStrings>  
  2.    <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=SchoolDB;" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Code Chamber

Step 5: In the code chamber we will write the code so that our application works.

Adding the following namespaces on namespace section of your code behind page-
  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.Data;  
  8. using System.Data.SqlClient;  
  9. using System.IO;  
  10. using System.ConFigureuration;  
Now your page looks like the following:

Code behind Page
  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.Data;  
  8. using System.Data.SqlClient;  
  9. using System.IO;  
  10. using System.Configuration;  
  11. public partial class GridViewImageUploading: System.Web.UI.Page   
  12. {  
  13.     SqlConnection con;  
  14.     SqlDataAdapter da;  
  15.     DataSet ds;  
  16.     SqlCommand cmd;  
  17.     string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  
  18.     protected void Page_Load(object sender, EventArgs e)  
  19.     {  
  20.         if (!IsPostBack)   
  21.         {  
  22.             ImageData();  
  23.         }  
  24.     }  
  25.     protected void upload_Click(object sender, EventArgs e)  
  26.     {  
  27.         try   
  28.         {  
  29.             string filename = Path.GetFileName(fileupload.PostedFile.FileName);  
  30.             fileupload.SaveAs(Server.MapPath("~/Images/" + filename));  
  31.             con = new SqlConnection(connStr);  
  32.             con.Open();  
  33.             cmd = new SqlCommand("insert into Image_Details (ImageName,Image) values(@ImageName,@Image)", con);  
  34.             cmd.Parameters.AddWithValue("@ImageName", filename);  
  35.             cmd.Parameters.AddWithValue("@Image""Images/" + filename);  
  36.             cmd.ExecuteNonQuery();  
  37.             ImageData();  
  38.         }   
  39.         catch (Exception ex)  
  40.         {  
  41.             upload.Text = ex.Message;  
  42.         }  
  43.     }  
  44.     protected void ImageData()  
  45.     {  
  46.         con = new SqlConnection(connStr);  
  47.         con.Open();  
  48.         da = new SqlDataAdapter("select * from Image_Details", con);  
  49.         ds = new DataSet();  
  50.         da.Fill(ds);  
  51.         gvImage.DataSource = ds;  
  52.         gvImage.DataBind();  
  53.     }  
  54.     // edit event    
  55.     protected void gvImage_RowEditing(object sender, GridViewEditEventArgs e)  
  56.     {  
  57.         gvImage.EditIndex = e.NewEditIndex;  
  58.         ImageData();  
  59.   
  60.     }  
  61.     // update event    
  62.     protected void gvImage_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  63.     {  
  64.         //find image id of edit row    
  65.         string imageId = gvImage.DataKeys[e.RowIndex].Value.ToString();  
  66.         // find values for update    
  67.         TextBox name = (TextBox) gvImage.Rows[e.RowIndex].FindControl("txt_Name");  
  68.         FileUpload FileUpload1 = (FileUpload) gvImage.Rows[e.RowIndex].FindControl("FileUpload1");  
  69.         con = new SqlConnection(connStr);  
  70.         string path = "~/Images/";  
  71.         if (FileUpload1.HasFile)   
  72.         {  
  73.             path += FileUpload1.FileName;  
  74.             //save image in folder    
  75.             FileUpload1.SaveAs(MapPath(path));  
  76.         }  
  77.         else  
  78.         {  
  79.             // use previous user image if new image is not changed    
  80.             Image img = (Image) gvImage.Rows[e.RowIndex].FindControl("img_user");  
  81.             path = img.ImageUrl;  
  82.         }  
  83.         SqlCommand cmd = new SqlCommand("update Image_Details set ImageName='" + name.Text + "',image='" + path + "'  where ImageId=" + imageId + "", con);  
  84.         con.Open();  
  85.         cmd.ExecuteNonQuery();  
  86.         con.Close();  
  87.         gvImage.EditIndex = -1;  
  88.         ImageData();  
  89.     }  
  90.     // cancel edit event    
  91.     protected void gvImage_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  92.     {  
  93.         gvImage.EditIndex = -1;  
  94.         ImageData();  
  95.     }  
  96.     //delete event    
  97.     protected void gvImage_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  98.     {  
  99.         GridViewRow row = (GridViewRow) gvImage.Rows[e.RowIndex];  
  100.         Label lbldeleteid = (Label) row.FindControl("lblImgId");  
  101.         Label lblDeleteImageName = (Label) row.FindControl("lblImageName");  
  102.         con = new SqlConnection(connStr);  
  103.         con.Open();  
  104.         SqlCommand cmd = new SqlCommand("delete FROM Image_Details where ImageId='" + Convert.ToInt32(gvImage.DataKeys[e.RowIndex].Value.ToString()) + "'", con);  
  105.         cmd.ExecuteNonQuery();  
  106.         con.Close();  
  107.         ImageDeleteFromFolder(lblDeleteImageName.Text);  
  108.         ImageData();  
  109.     }  
  110.     /// <summary>  
  111.     /// This function is used to delete image from folder when deleting in gridview.  
  112.     /// </summary>  
  113.     /// <param name="imagename">image name</param>  
  114.     protected void ImageDeleteFromFolder(string imagename)  
  115.     {  
  116.         string file_name = imagename;  
  117.         string path = Server.MapPath(@  
  118.         "~/Images/" + imagename);  
  119.         FileInfo file = new FileInfo(path);  
  120.         if (file.Exists) //check file exsit or not  
  121.         {  
  122.             file.Delete();  
  123.             lblResult.Text = file_name + " file deleted successfully";  
  124.             lblResult.ForeColor = System.Drawing.Color.Green;  
  125.         }   
  126.         else  
  127.         {  
  128.             lblResult.Text = file_name + " This file does not exists ";  
  129.             lblResult.ForeColor = System.Drawing.Color.Red;  
  130.         }  
  131.     }  
Output

When no data is uploaded.

When no data is uploaded
                                                                           Figure 5
On first image upload-

On fist image upload
                                                                              Figure 6

One more image uploaded-

On more image upload
                                                                                 Figure 7
Two more images uploaded-

On too more image upload
                                                                             Figure 8
On deleting an image-

On Image deletion
                                                                                    Figure 9
On Edit button click-

On Edit button click
                                                                                 Figure 10
On Image Pupation-

On Image Pupation
                                                                                 Figure 11

Hope you liked this. Have a good day. Thank you for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all