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  

USE [SchoolDB]  
GO  
  
/****** Object:  Table [dbo].[Image_Details]    Script Date: 07.09.2015 4:34:24 PM ******/  
SET ANSI_NULLS ON  
GO  
  
SET QUOTED_IDENTIFIER ON  
GO  
  
SET ANSI_PADDING ON  
GO  
  
CREATE TABLE [dbo].[Image_Details](  
    [ImageId] [int] IDENTITY(1,1) NOT NULL,  
    [ImageName] [varchar](50) NULL,  
    [Image] [nvarchar](max) NULL  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  
GO  
  
SET ANSI_PADDING OFF  
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: 

<h3 style="color: #0000FF; font-style: italic">Display Image and update, delete in GridView Using ASP.NET</h3>  
<div>  
    <asp:FileUpload ID="fileupload" runat="server" />  
    <asp:Button ID="upload" runat="server" Font-Bold="true" Text="Upload" OnClick="upload_Click" />  
<asp:Label ID="lblResult" runat="server"/>

    <br />  
    <br />  
</div>  
<div>  
    <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">  
        <Columns>  
            <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px">  
                <ItemTemplate>  
                    <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>  
                </ItemTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField HeaderText="Name" HeaderStyle-Width="200px">  
                <ItemTemplate>  
                    <asp:Label ID="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>  
                </ItemTemplate>  
                <EditItemTemplate>  
                    <asp:TextBox ID="txt_Name" runat="server" Text='<%# Eval("ImageName") %>'></asp:TextBox>  
                </EditItemTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField HeaderText="Image" HeaderStyle-Width="200px">  
                <ItemTemplate>  
                    <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>' Height="80px" Width="100px" />  
                </ItemTemplate>  
                <EditItemTemplate>  
                    <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("Image") %>' Height="80px" Width="100px" />  
                    <br />  
                    <asp:FileUpload ID="FileUpload1" runat="server" />  
                </EditItemTemplate>  
            </asp:TemplateField>  
            <asp:TemplateField HeaderStyle-Width="150px">  
                <ItemTemplate>  
                    <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>  
                    <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton>  
                </ItemTemplate>  
                <EditItemTemplate>  
                    <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>  
                    <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>  
                </EditItemTemplate>  
            </asp:TemplateField>  
        </Columns>  
    </asp:GridView>  
</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:  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewImageUploading.aspx.cs" Inherits="GridViewImageUploading" %>  
  
<!DOCTYPE html>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title>An article by Upendra Pratap Shahi</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
        <h3 style="color: #0000FF; font-style: italic">Display Image and update, delete in GridView Using ASP.NET</h3>  
        <div>  
            <asp:FileUpload ID="fileupload" runat="server" />  
            <asp:Button ID="upload" runat="server" Font-Bold="true" Text="Upload" OnClick="upload_Click" />  
<asp:Label ID="lblResult" runat="server"/>

            <br />  
            <br />  
        </div>  
        <div>  
            <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">  
                <Columns>  
                    <asp:TemplateField HeaderText="Sr.No" HeaderStyle-Width="200px">  
                        <ItemTemplate>  
                            <asp:Label ID="lblImgId" runat="server" Text='<%#Container.DataItemIndex+1%>'></asp:Label>  
                        </ItemTemplate>  
                    </asp:TemplateField>  
                    <asp:TemplateField HeaderText="Name" HeaderStyle-Width="200px">  
                        <ItemTemplate>  
                            <asp:Label ID="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>  
                        </ItemTemplate>  
                        <EditItemTemplate>  
                            <asp:TextBox ID="txt_Name" runat="server" Text='<%# Eval("ImageName") %>'></asp:TextBox>  
                        </EditItemTemplate>  
                    </asp:TemplateField>  
                    <asp:TemplateField HeaderText="Image" HeaderStyle-Width="200px">  
                        <ItemTemplate>  
                            <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>'  
                                Height="80px" Width="100px" />  
                        </ItemTemplate>  
                        <EditItemTemplate>  
                            <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("Image") %>'  
                                Height="80px" Width="100px" /><br />  
                            <asp:FileUpload ID="FileUpload1" runat="server" />  
                        </EditItemTemplate>  
                    </asp:TemplateField>  
                    <asp:TemplateField HeaderStyle-Width="150px">  
                        <ItemTemplate>  
                            <asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>  
                            <asp:LinkButton ID="LkB11" runat="server" CommandName="Delete">Delete</asp:LinkButton>  
                        </ItemTemplate>  
                        <EditItemTemplate>  
                            <asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>  
                            <asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>  
                        </EditItemTemplate>  
                    </asp:TemplateField>  
                </Columns>  
            </asp:GridView>  
        </div>  
    </form>  
</body>  
</html>

Your design looks like following figure:

design

Figure 4

Configure Chamber

Add the following code in Web.configure.

<connectionStrings>  
   <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=SchoolDB;" providerName="System.Data.SqlClient"/>  
</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-

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Data;  
using System.Data.SqlClient;  
using System.IO;  
using System.ConFigureuration;  

Now your page looks like the following:

Code behind Page 

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Data;  
using System.Data.SqlClient;  
using System.IO;  
using System.Configuration;  
public partial class GridViewImageUploading: System.Web.UI.Page   
{  
    SqlConnection con;  
    SqlDataAdapter da;  
    DataSet ds;  
    SqlCommand cmd;  
    string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;  
    protected void Page_Load(object sender, EventArgs e)  
    {  
        if (!IsPostBack)   
        {  
            ImageData();  
        }  
    }  
    protected void upload_Click(object sender, EventArgs e)  
    {  
        try   
        {  
            string filename = Path.GetFileName(fileupload.PostedFile.FileName);  
            fileupload.SaveAs(Server.MapPath("~/Images/" + filename));  
            con = new SqlConnection(connStr);  
            con.Open();  
            cmd = new SqlCommand("insert into Image_Details (ImageName,Image) values(@ImageName,@Image)", con);  
            cmd.Parameters.AddWithValue("@ImageName", filename);  
            cmd.Parameters.AddWithValue("@Image", "Images/" + filename);  
            cmd.ExecuteNonQuery();  
            ImageData();  
        }   
        catch (Exception ex)  
        {  
            upload.Text = ex.Message;  
        }  
    }  
    protected void ImageData()  
    {  
        con = new SqlConnection(connStr);  
        con.Open();  
        da = new SqlDataAdapter("select * from Image_Details", con);  
        ds = new DataSet();  
        da.Fill(ds);  
        gvImage.DataSource = ds;  
        gvImage.DataBind();  
    }  
    // edit event    
    protected void gvImage_RowEditing(object sender, GridViewEditEventArgs e)  
    {  
        gvImage.EditIndex = e.NewEditIndex;  
        ImageData();  
  
    }  
    // update event    
    protected void gvImage_RowUpdating(object sender, GridViewUpdateEventArgs e)  
    {  
        //find image id of edit row    
        string imageId = gvImage.DataKeys[e.RowIndex].Value.ToString();  
        // find values for update    
        TextBox name = (TextBox) gvImage.Rows[e.RowIndex].FindControl("txt_Name");  
        FileUpload FileUpload1 = (FileUpload) gvImage.Rows[e.RowIndex].FindControl("FileUpload1");  
        con = new SqlConnection(connStr);  
        string path = "~/Images/";  
        if (FileUpload1.HasFile)   
        {  
            path += FileUpload1.FileName;  
            //save image in folder    
            FileUpload1.SaveAs(MapPath(path));  
        }  
        else  
        {  
            // use previous user image if new image is not changed    
            Image img = (Image) gvImage.Rows[e.RowIndex].FindControl("img_user");  
            path = img.ImageUrl;  
        }  
        SqlCommand cmd = new SqlCommand("update Image_Details set ImageName='" + name.Text + "',image='" + path + "'  where ImageId=" + imageId + "", con);  
        con.Open();  
        cmd.ExecuteNonQuery();  
        con.Close();  
        gvImage.EditIndex = -1;  
        ImageData();  
    }  
    // cancel edit event    
    protected void gvImage_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
    {  
        gvImage.EditIndex = -1;  
        ImageData();  
    }  
    //delete event    
    protected void gvImage_RowDeleting(object sender, GridViewDeleteEventArgs e)  
    {  
        GridViewRow row = (GridViewRow) gvImage.Rows[e.RowIndex];  
        Label lbldeleteid = (Label) row.FindControl("lblImgId");  
        Label lblDeleteImageName = (Label) row.FindControl("lblImageName");  
        con = new SqlConnection(connStr);  
        con.Open();  
        SqlCommand cmd = new SqlCommand("delete FROM Image_Details where ImageId='" + Convert.ToInt32(gvImage.DataKeys[e.RowIndex].Value.ToString()) + "'", con);  
        cmd.ExecuteNonQuery();  
        con.Close();  
        ImageDeleteFromFolder(lblDeleteImageName.Text);  
        ImageData();  
    }  
    /// <summary>  
    /// This function is used to delete image from folder when deleting in gridview.  
    /// </summary>  
    /// <param name="imagename">image name</param>  
    protected void ImageDeleteFromFolder(string imagename)  
    {  
        string file_name = imagename;  
        string path = Server.MapPath(@  
        "~/Images/" + imagename);  
        FileInfo file = new FileInfo(path);  
        if (file.Exists) //check file exsit or not  
        {  
            file.Delete();  
            lblResult.Text = file_name + " file deleted successfully";  
            lblResult.ForeColor = System.Drawing.Color.Green;  
        }   
        else  
        {  
            lblResult.Text = file_name + " This file does not exists ";  
            lblResult.ForeColor = System.Drawing.Color.Red;  
        }  
    }  
}

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.