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?
- Now,Let’s Start ,Open visual studio add new empty website
- File>New >Web Site >Empty Web Site”
- 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
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Gridview with Detail Rows for each Item
- How to set different ids for each control in each gridview row
- MVC razor partial view radio button selection for each row in model
- Enable browser back button for repeater control with update panel in asp.net c# with master page
- (WPF) How to change button image background in listBox with buttons in each line ?
- How to add a column in a Dataset, with a variable value (int) for each row
- Button click in template field of asp.net gridview doesn't work with update panel
- Adding a image button to a gridview header in c# with on click event
- Delete Button for each ListView Row
- For each with a dynamic list?
- How to update image with JavaScript and ASP.NET MVC?
- Entity framework terms used with asp net mvc app
- WPF button with image doesn't appear
- Task Factory for each loop with await
- Vertical line across multiple line charts with value display for each chart in Winforms
- Image and label inside a button update on click event wpf
- C# one letter on each row in gridview
- combobox with for each loop
- How to save row changes in DevExpress GridView with the EmbeddedNavigator
- ASP Net Text box with Google like dropdown search values
- Getting stackoverflow exception with Parallel for each , is this due to thread saftey?
- Get GridView row index from a template field button
- What's the recommended way for console applications to talk with each other?
- How to test ASP NET ashx Handler With File Attached
- Problem with ImageUrl, adding automaticly a FOLDER name to the URL created for the image
- New row inserted for each page refresh
- How to show checked radio button in Razor edit view Asp net core mvc
- ASP NET MVC RAZOR Upload Multiple Images FileList
- Variable number of method parameters with different types for each of them
- Onclick Button open a new Window only with Image inside
- Loading a Resource file with XElement
- Mathnet Numerics with Intel MKL running much slower on Intel Xeon Gold than an old i7-7700HQ laptop
- How can I add a new route on my existing asp.net-mvc site without a large rewrite?
- Parse XML with C#
- Wildcard in MapPageRoute
- .Sort(Function(x, y) -> re-arranges list when there is nothing to sort (i.e., all sort fields have the same value)
- Argh! How do you correctly update the SelectedValue of a ComboBox on initialization?
- C# Can you examine an exception without catching?
- Clear Immediate Window from Code in .NET
- Correct way to seed DB with users when using Web Api Identity and Tokens
- ServiceStack: JsonServiceClient usage without IReturn in DTO
- How to configure NLog programmatically for Async target?
- Dependency injection : should I completely hide implementation and take a dependency on the container or keep my implementation and constructor public
- What is a good way to allow two-way binding to a IQueryable with a DataGridView?
- Can I force the use of the 'using' statement for instances of my IDisposable class?
- Inserting small float value to SQL Server using C# and Entity Framework
- Gridview and List<>
- How to interrupt existing IObservable sequence?
- Add new row at bottom of datagridview in Winform
- How do you send a request directly to .DLL (not .ASPX, .ASHX, etc.)?