Binding Image With GridView And Update Image in GridView Without Using Database

This article shows you how to bind data in GridView controls without using any database. Also, we will learn here how to bind controls with data without using a database. Additionally,  how to handle gridview common event in this will be discussed. Here I’ve described more events such as Edit, Update and Delete event.

This is using Image uploading and binding in GridView and then updating image in GridView.

Also read the following articles:

 
Binding Data in ListView on LinkButton Click

Initial Chamber

Step 1


Open Visual Studio and create an empty website, then provide a suitable name such as BindImageWithoutDB.

Step 2

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

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

Design Chamber

Step-3

Open the BindImageWithoutDB.aspx file and write some code for the design of the application.

Step3.1

Put stylesheet code in head chamber of page.

Set your style of page according to your need of design as in the following:
  1. <style type="text/css">  
  2. body {  
  3. color: #333;  
  4. text-align: center;  
  5. background-color: aqua;  
  6. }  
  7. </style>  
Step3.2

Choose control from toolbox and put on your design page as in the following code snippet:
  1. <div style="float: left">  
  2.             <asp:Label ID="Label1" runat="server" Text="Display an Image :"></asp:Label>  
  3.             <asp:FileUpload ID="FileUpload1" runat="server" />  
  4.             <asp:Button ID="btnUpload" runat="server" Text="Display" OnClick="UploadImage" />  
  5.         </div>  
  6.         <asp:Label ID="lblResult" runat="server" />  
  7.         <br />  
  8.         <br />  
  9.         <div style="float: left">  
  10.             <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" DataKeyNames="imgname" CellPadding="4"  
  11.                 OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" HeaderStyle-BackColor="Tomato">  
  12.                 <Columns>  
  13.                     <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px">  
  14.                         <ItemTemplate>  
  15.                             <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>  
  16.                         </ItemTemplate>  
  17.                     </asp:TemplateField>  
  18.                     <asp:TemplateField HeaderText="Date">  
  19.                         <ItemTemplate>  
  20.                             <asp:Label ID="lblDate" runat="server" ClientIDMode="Static" Text='<%# DataBinder.Eval(Container.DataItem,"imgdate") %>'></asp:Label>  
  21.                         </ItemTemplate>  
  22.                          
  23.                     </asp:TemplateField>  
  24.                     <asp:TemplateField HeaderText="Name">  
  25.                         <ItemTemplate>  
  26.                             <asp:Label ID="lblTextBox1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"imgname") %>'></asp:Label>  
  27.                         </ItemTemplate>  
  28.                     </asp:TemplateField>  
  29.                     <asp:TemplateField HeaderText="Image Name">  
  30.                         <ItemTemplate>  
  31.                             <asp:Image ID="Image" runat="server" Height="100px" Width="20%" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"imgurl") %>' />  
  32.                         </ItemTemplate>  
  33.                         <EditItemTemplate>  
  34.                             <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("imgurl") %>'  
  35.                                 Height="80px" Width="100px" /><br />  
  36.                             <asp:FileUpload ID="FileUpload1" runat="server" />  
  37.                         </EditItemTemplate>  
  38.                     </asp:TemplateField>  
  39.                     <asp:TemplateField HeaderStyle-Width="150px">  
  40.                         <ItemTemplate>  
  41.                             <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>  
  42.                             <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton>  
  43.                         </ItemTemplate>  
  44.                         <EditItemTemplate>  
  45.                             <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>  
  46.                             <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>  
  47.                         </EditItemTemplate>  
  48.                     </asp:TemplateField>  
  49.                 </Columns>  
  50.             </asp:GridView>  
  51.         </div  
Design of page looks like the following:



Here, I've designed the GridView Control and uploader used some property as in the following code snippet:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="BindImageWithoutDB.aspx.cs" Inherits="BindImageWithoutDB" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>C-sharp corner by Upendra</title>  
  8.       
  9.     <style type="text/css">  
  10.         body {  
  11.             color: #333;  
  12.             text-align: center;  
  13.             background-color: aqua;  
  14.         }  
  15.     </style>  
  16. </head>  
  17. <body>  
  18.     <form id="form1" runat="server">  
  19.         <div style="float: left">  
  20.             <asp:Label ID="Label1" runat="server" Text="Display an Image :"></asp:Label>  
  21.             <asp:FileUpload ID="FileUpload1" runat="server" />  
  22.             <asp:Button ID="btnUpload" runat="server" Text="Display" OnClick="UploadImage" />  
  23.         </div>  
  24.         <asp:Label ID="lblResult" runat="server" />  
  25.         <br />  
  26.         <br />  
  27.         <div style="float: left">  
  28.             <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" DataKeyNames="imgname" CellPadding="4"  
  29.                 OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" HeaderStyle-BackColor="Tomato">  
  30.                 <Columns>  
  31.                     <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px">  
  32.                         <ItemTemplate>  
  33.                             <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>  
  34.                         </ItemTemplate>  
  35.                     </asp:TemplateField>  
  36.                     <asp:TemplateField HeaderText="Date">  
  37.                         <ItemTemplate>  
  38.                             <asp:Label ID="lblDate" runat="server" ClientIDMode="Static" Text='<%# DataBinder.Eval(Container.DataItem,"imgdate") %>'></asp:Label>  
  39.                         </ItemTemplate>  
  40.                          
  41.                               
  42.                     </asp:TemplateField>  
  43.                     <asp:TemplateField HeaderText="Name">  
  44.                         <ItemTemplate>  
  45.                             <asp:Label ID="lblTextBox1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"imgname") %>'></asp:Label>  
  46.                         </ItemTemplate>  
  47.                     </asp:TemplateField>  
  48.                     <asp:TemplateField HeaderText="Image Name">  
  49.                         <ItemTemplate>  
  50.                             <asp:Image ID="Image" runat="server" Height="100px" Width="20%" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"imgurl") %>' />  
  51.                         </ItemTemplate>  
  52.                         <EditItemTemplate>  
  53.                             <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("imgurl") %>'  
  54.                                 Height="80px" Width="100px" /><br />  
  55.                             <asp:FileUpload ID="FileUpload1" runat="server" />  
  56.                         </EditItemTemplate>  
  57.                     </asp:TemplateField>  
  58.                     <asp:TemplateField HeaderStyle-Width="150px">  
  59.                         <ItemTemplate>  
  60.                             <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>  
  61.                             <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton>  
  62.                         </ItemTemplate>  
  63.                         <EditItemTemplate>  
  64.                             <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>  
  65.                             <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>  
  66.                         </EditItemTemplate>  
  67.                     </asp:TemplateField>  
  68.                 </Columns>  
  69.             </asp:GridView>  
  70.         </div>  
  71.   
  72.     </form>  
  73. </body>  
  74. </html>  
Your design looks like the following figure:



CODE CHAMBER

Step 4

In the code chamber we will write some code so that our application works.
Adding the following namespaces under namespace section of your code behind page.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
Code behind Page
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8.   
  9. public partial class BindImageWithoutDB : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         if (!IsPostBack)  
  14.         {  
  15.             BindImage();  
  16.         }  
  17.     }  
  18.   
  19.     public class clsImg  
  20.     {  
  21.         //property for image uploading  
  22.         public string imgurl { getset; }  
  23.         public string imgname { getset; }  
  24.         public DateTime imgdate { getset; }  
  25.     }  
  26.     protected void BindImage()  
  27.     { 
  28.         string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/TestImage/"));  
  29.         List<clsImg> images = new List<clsImg>(filesindirectory.Count());  
  30.         //file time  
  31.         DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath("~/Images/TestImage/"));  
  32.         var files = from file in DirInfo.EnumerateFiles()  
  33.                     orderby file.LastWriteTime descending  
  34.                     select file;  
  35.         DateTime lastModifie = System.DateTime.Now;  
  36.         DateTime creationTime;  
  37.         DateTime lastAccessTime;  
  38.         foreach (var fi in files)  
  39.         {  
  40.             lastModifie = fi.LastWriteTimeUtc;  
  41.             creationTime = fi.CreationTimeUtc;  
  42.             lastAccessTime = fi.LastWriteTimeUtc;  
  43.             images.Add(new clsImg { imgdate = lastModifie, imgname = fi.Name.ToString(), imgurl = String.Format("~/Images/TestImage/{0}", System.IO.Path.GetFileName(fi.Name.ToString())) });  
  44.         }  
  45.   
  46.         GridView1.DataSource = images;  
  47.         GridView1.DataBind();  
  48.     }  
  49.     protected void UploadImage(object sender, EventArgs e)  
  50.     {  
  51.         if (FileUpload1.HasFile)  
  52.         {  
  53.             string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);  
  54.             FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/TestImage/") + fileName);  
  55.             Response.Redirect(Request.Url.AbsoluteUri);  
  56.         }  
  57.     }  
  58.     //editing event  
  59.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  60.     {  
  61.         GridView1.EditIndex = e.NewEditIndex;  
  62.         BindImage();  
  63.     }  
  64.     //row updation event  
  65.     //here we try to update modification time but this I can't achieve this currently  
  66.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  67.     {  
  68.         //find image id of edit row  
  69.         string imageId = GridView1.DataKeys[e.RowIndex].Value.ToString();  
  70.         // find values for update  
  71.         Label name = (Label)GridView1.Rows[e.RowIndex].FindControl("lblTextBox1");  
  72.          
  73.         FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");  
  74.         string path = "~/Images/TestImage/";  
  75.         string path1;  
  76.         if (FileUpload1.HasFile)  
  77.         {  
  78.             ImageDeleteFromFolder(name.Text.ToString());  
  79.             //path += FileUpload1.FileName;  
  80.             path += FileUpload1.FileName;  
  81.               
  82.             //save image in folder  
  83.             FileUpload1.SaveAs(MapPath(path));  
  84.         }  
  85.         else  
  86.         {  
  87.             // use previous user image if new image is not changed  
  88.             Image img = (Image)GridView1.Rows[e.RowIndex].FindControl("img_user");  
  89.             path = img.ImageUrl;  
  90.         }  
  91.         GridView1.EditIndex = -1;  
  92.         BindImage();  
  93.     }  
  94.     //cancelation event  
  95.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  96.     {  
  97.         GridView1.EditIndex = -1;  
  98.         BindImage();  
  99.     }  
  100.     //deleting event  
  101.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  102.     {  
  103.         GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];  
  104.         // Label lbldeleteid = (Label)row.FindControl("lblTextBox1");  
  105.         Label lblDeleteImageName = (Label)row.FindControl("lblTextBox1");  
  106.         //con = new SqlConnection(connStr);  
  107.         ImageDeleteFromFolder(lblDeleteImageName.Text.ToString());  
  108.         BindImage();  
  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(@"~/Images/TestImage/" + imagename);  
  118.         FileInfo file = new FileInfo(path);  
  119.         if (file.Exists)//check file exsit or not  
  120.         {  
  121.             file.Delete();  
  122.             lblResult.Text = file_name + " file deleted successfully";  
  123.             lblResult.ForeColor = System.Drawing.Color.Green;  
  124.         }  
  125.         else  
  126.         {  
  127.             lblResult.Text = file_name + " This file does not exists ";  
  128.             lblResult.ForeColor = System.Drawing.Color.Red;  
  129.         }  
  130.     }  
  131. }  
Output





I hope you liked this. Have a good day. Thank you for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all