Here I have created sample that populates Grid view contains Image Details, in this I have made the functionality that delete image details from the database and deletes the image physically as well.
HTML
<div>
<asp:GridView ID="gvImages" DataKeyNames="Id" EmptyDataTex="No image" runat="server"
AutoGenerateColumns="False" Font-Names="Arial" OnRowCommand="gvImages_RowCommand">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Image Id" Visible="true" />
<asp:BoundField DataField="FilePath" HeaderText="Path" Visible="true" />
<asp:BoundField DataField="FileName" HeaderText="Image Name" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("Id") %>' CommandName="Delete"
runat="server" OnClientClick="return confirm('Do you want to delete this Image');">
Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
Namespaces
using System.Data;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetImages();
}
}
protected void gvImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow);
int imageId = Convert.ToInt32(row.Cells[0].Text);
this.DeleteImage(imageId);
string path = row.Cells[1].Text;
string imagePath = new Uri(Server.MapPath(path)).AbsolutePath;
File.Delete(imagePath);
Response.Redirect("DeleteImageUsingGridView.aspx");
}
}
private void GetImages()
{
string constr = ConfigurationManager.ConnectionStrings["constrSample"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, FileName, FilePath FROM tblImages", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
gvImages.DataSource = dt;
gvImages.DataBind();
}
private void DeleteImage(int imageId)
{
string constr = ConfigurationManager.ConnectionStrings["constrSample"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM tblImages WHERE Id=@ImageId", con))
{
cmd.Parameters.AddWithValue("@ImageId", imageId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
gvImages.DataSource = dt;
gvImages.DataBind();
}
Screenshot