As we know, the GridView control is very popular and useful for developers who want to display data in a table format and perform actions such as insert, update, and delete.
Often, we require a user management module to view and edit user information. I am also working on a similar requirement, and I want to share my knowledge with other developers so they can benefit from this post when facing similar tasks.
We are going to create a GridView to display employee information along with their profile pictures. Each row will have edit and delete buttons so that the admin can update user details.
We need to have a FileUpload button for each row in the GridView so that the admin can update the profile picture of the user, just like the image below.
Our main task is: How to upload and update an image in an edit mode GridView using the upload button for each row?
Now, let's begin. Open Visual Studio and add a new empty website by navigating to File > New > Web Site > Empty Web Site.
Next, 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.
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]
Now copy-paste the below code in your webforms.
<%@ 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>
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
Button1_Click:
bindgridview:
GridView Events:
ImageDeleteFromFolder:
Above code provides functionality to upload images, perform CRUD operations on employee records, and handle image deletion in an ASP.NET Web Forms application.
I am using some GridView events for insert, delete, and update operations. Below are the listed events:
1) OnRowCancelingEdit: This event fires when the Cancel button is clicked while the row is in edit mode.
2) OnRowEditing: This event fires when a row's Edit button is clicked, but before the GridView control enters edit mode.
3) OnRowUpdating: This event fires when the 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.