As we know that Gridview control is very popular and useful for every developer who wants to show the data in table format and want to perform some action on it like insert, update, delete.
Many times we need a user management module to see the information and edit the information of the user.I am also working with the same type of requirement, so I want to share my knowledge with other developers so they can benefit from this post when they face the same type of task.
We are going to create a Gridview in which we will show the Employee’s information with their profile picture. Each row has an edit and deletes button so that the admin can update the user detail.

We need to have a FileUpload button for each row in Gridview on the click of the edit so the admin can update the profile picture of the user. Just like the below image.

Basically our task is :How to upload and update an image in an edit mode gridview using the upload button for each row?

  1. Now,Let’s Start ,Open visual studio add new empty website
  2. File>New >Web Site >Empty Web Site”
  3. Now add a folder on your website for storing uploaded images.

 

To start with Gridview Image operation we need a database. For that I have created a database table named “Employee“with Column  Id, Name, City,Salary ,ProfilePicture,PictureName.

Sql Table Script

CREATE TABLE [dbo].[Employee](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](150) NULL,
    [City] [nvarchar](500) NULL,
    [Salary] [decimal](18, 2) NULL,
    [ProfilePicture] [nvarchar](500) NULL,
    [PictureName] [nvarchar](150) NULL,
 CONSTRAINT [PK_Employee_1] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

 

In this post, we will cover the following points:-

  • Binding Image With GridView And Updating Image In GridView
  • How to update image stored on disk and path in database in asp.net gridview
  • Retrive Images and Update Images in Database from Gridview?
  • On click of edit button of gridview, update image in DataBase

Now copy-paste the below code in your webforms.

Aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <fieldset>
                <legend>Add Employees</legend>
                <asp:TextBox ID="txtname" runat="server" placeholder="Name"></asp:TextBox>
                <br />
                <asp:TextBox ID="txtcity" runat="server"  placeholder="City"></asp:TextBox>
                <br />
                <asp:TextBox ID="txtsalary" runat="server" type="number" placeholder="Salary"></asp:TextBox>
                <br />
                <asp:FileUpload ID="FileUpload1" runat="server" />
                <br />
                <br />
                <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
            </fieldset>
            <table class="auto-style1">
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Height="365px" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
                            <AlternatingRowStyle BackColor="White" />
                            <Columns>
                                <asp:TemplateField HeaderText="Name">
                                    <ItemTemplate>
                                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                                    </EditItemTemplate>

<HeaderStyle Width="200px"></HeaderStyle>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="City">
                                    <ItemTemplate>
                                        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtCity" runat="server" Text='<%# Eval("City") %>'></asp:TextBox>
                                    </EditItemTemplate>

<HeaderStyle Width="200px"></HeaderStyle>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Salary">
                                    <ItemTemplate>
                                        <asp:Label ID="lblSalary" runat="server" Text='<%# Eval("Salary") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtSalary" runat="server" type="number" Text='<%# Eval("Salary") %>'></asp:TextBox>
                                    </EditItemTemplate>

<HeaderStyle Width="200px"></HeaderStyle>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image Name">
                                    <ItemTemplate>
                                        <asp:Label ID="lblImageName" runat="server" Text='<%# Eval("PictureName") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtImageName" runat="server" Text='<%# Eval("PictureName") %>'></asp:TextBox>
                                    </EditItemTemplate>

<HeaderStyle Width="200px"></HeaderStyle>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image">
                                    <ItemTemplate>
                                        <asp:Image ID="Imagepath" runat="server" ImageUrl='<%# Eval("ProfilePicture") %>' Height="80px" Width="100px" />
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:Image ID="imgupload" runat="server" ImageUrl='<%# Eval("ProfilePicture") %>' Height="80px" Width="100px" />
                                        <br />
                                        <asp:FileUpload ID="FileUpload1" runat="server" />
                                    </EditItemTemplate>

<HeaderStyle Width="200px"></HeaderStyle>
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="linkedit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                                        <asp:LinkButton ID="linkdelete" runat="server" CommandName="Delete">Delete</asp:LinkButton>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:LinkButton ID="linkupdate" runat="server" CommandName="Update">Update</asp:LinkButton>
                                        <asp:LinkButton ID="linkcancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                                    </EditItemTemplate>

<HeaderStyle Width="150px"></HeaderStyle>
                                </asp:TemplateField>
                            </Columns>
                            <EditRowStyle BackColor="#7C6F57" />
                            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
                            <RowStyle BackColor="#E3EAEB" />
                            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                            <SortedAscendingCellStyle BackColor="#F8FAFA" />
                            <SortedAscendingHeaderStyle BackColor="#246B61" />
                            <SortedDescendingCellStyle BackColor="#D4DFE1" />
                            <SortedDescendingHeaderStyle BackColor="#15524A" />
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

 

Code Behind Code

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

public partial class GridView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=ADEQUATE-ASHOK\\SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=adk;Password=adk@1234");
    protected void Page_Load(object sender, EventArgs e)
    {
        bindgridview();

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.PostedFile != null)
        {
            string name = txtname.Text;
            string city = txtcity.Text;
            string salary = txtsalary.Text;
            string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(Server.MapPath("FileStorage/" + FileName)); //save picture into Images folder in the website
            string imagepath = "FileStorage/" + FileName;
            string query = "insert into Employee values (@Name,@City,@Salary,@ProfilePicture,@PictureName)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@City", city);
                cmd.Parameters.AddWithValue("@Salary", salary);
                cmd.Parameters.AddWithValue("@ProfilePicture", imagepath);
                cmd.Parameters.AddWithValue("@PictureName", FileName);
                con.Open();
                int i = cmd.ExecuteNonQuery();
                con.Close();
                if (i > 0)
                {
                    Response.Write("<script>alert('image uploaded successfully!')</script>");
                    bindgridview();
                }
                else
                {
                    Response.Write("<script>alert('something went wrong try later!')</script>");
                    bindgridview();
                }
            }


        }
    }

    public void bindgridview()
    {
        SqlCommand cmd = new SqlCommand("select * from Employee", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }


    }
    //edit event
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bindgridview();
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //finding Datakeynames from gridview(find image id of edit row) 
        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
        // find values for update from gridview   
        TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
        TextBox city = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
        TextBox salary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSalary");
        TextBox imagename = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtImageName");
        FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
        string path = "~/FileStorage/";
        if (FileUpload1.HasFile)
        {
            if (string.IsNullOrEmpty(imagename.Text))
            {
                imagename.Text = FileUpload1.FileName;
            }
            path += FileUpload1.FileName;
            //save image in folder    
            FileUpload1.SaveAs(MapPath(path));
            string query = "UPDATE Employee SET Name = @name, City = @city,Salary=@salary,ProfilePicture=@profilepicture,PictureName=@picturename Where Id =@id";
            using (SqlCommand command = new SqlCommand(query))
            {
                command.Connection = con;
                command.Parameters.AddWithValue("@name", name.Text);
                command.Parameters.AddWithValue("@city", city.Text);
                command.Parameters.AddWithValue("@salary", salary.Text);
                command.Parameters.AddWithValue("@profilepicture", path);
                command.Parameters.AddWithValue("@picturename", imagename.Text);
                command.Parameters.AddWithValue("@id", id);
                con.Open();
                command.ExecuteNonQuery();
                con.Close();
            }
            GridView1.EditIndex = -1;
            bindgridview();
        }
       
       
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bindgridview();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
        Label DeleteImageName = (Label)row.FindControl("lblImageName");
        con.Open();
        SqlCommand cmd = new SqlCommand("delete FROM Employee where Id='" + id + "'", con);
        cmd.ExecuteNonQuery();
        con.Close();
        ImageDeleteFromFolder(DeleteImageName.Text);
        bindgridview();
    }
    protected void ImageDeleteFromFolder(string imagename)
    {
        string filename = imagename;
        string path = Server.MapPath(@"~/FileStorage/" + imagename);
        FileInfo file = new FileInfo(path);
        if (file.Exists) //checking image is exsit or not  
        {
            file.Delete();
            Response.Write("<script>alert('" + filename + "'+'file deleted successfully')</script>");
        }
        else
        {
            Response.Write("<script>alert('" + filename + "'+'This file does not exists')</script>");
        }
    }
}

 

Now you can perform update ,delete operation in GridView

I am using some Grandview event for insert, delete, update operation, I have listed all the event below.

1) Onrowcancelingedit: this event fire when the Cancel is clicked when the row in edit mode.

2) Onrowediting:  this event fire when a row’s Edit button is clicked, but before the GridView control enters edit mode.

3) Onrowupdating: this event fire, Update button is clicked, but before the GridView control updates the row

4) Onrowdeleting: this event executes when a row’s Delete button is clicked.

5)OnRowCommand: this event executes when a button is clicked in the GridView control.

The post Update an Image with Upload Button For Each Row in Gridview-Asp .Net appeared first on Software Development | Programming Tutorials.



Read More Articles