Delete data from Database and Image from Folder (Directory) using C# and VB.Net in ASP.Net

Last Reply 26 days ago By pandeyism

Posted 26 days ago

I am trying to perform curd operation everything is working fine but when I delete a entry from gridview.

it is being deleted successfully but it is not being deleted from folder where all the images are being stored.

code behind

namespace Jobopedia
{
    public partial class SP_edit : System.Web.UI.Page
    {
        SqlConnection con;
        SqlDataAdapter da;
        DataSet ds;
        SqlCommand cmd;
        string constr = ConfigurationManager.ConnectionStrings["Q_SS_regnConnectionString1"].ConnectionString;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                //this.BindGrid();
                ImageData();
            }
        }
        protected void ImageData()
        {
            con = new SqlConnection(constr);
            con.Open();
            da = new SqlDataAdapter("select * from Q_SP_Afterlogin", con);
            ds = new DataSet();
            da.Fill(ds);
            gvImage.DataSource = ds;
            gvImage.DataBind();
        }        

        protected void gvImage_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridViewRow row = (GridViewRow)gvImage.Rows[e.RowIndex];
            Label Id = (Label)row.FindControl("lblId");
            Label Bussiness_name = (Label)row.FindControl("lblBname");
            Label city = (Label)row.FindControl("lblcity");
            Label name = (Label)row.FindControl("lblname");
            Label toll_free = (Label)row.FindControl("lbltoll");
            Label website_link = (Label)row.FindControl("lblweb");
            Label payment_mode = (Label)row.FindControl("lblpay");
            Label email = (Label)row.FindControl("lblmail");
            //Label Images = (Label)row.FindControl("Image1");
            con = new SqlConnection(constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("delete FROM Q_SP_Afterlogin where Id='" + Convert.ToInt32(gvImage.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
            cmd.ExecuteNonQuery();
            con.Close();
            ImageDeleteFromFolder(name.Text);
            ImageData();
        }
        protected void ImageDeleteFromFolder(string Images)
        {
            string file_name = Images;
            string path = Server.MapPath("~/uploads/");
            FileInfo file = new FileInfo(path);
            if (file.Exists) //check file exsit or not  
            {
                file.Delete();
                lblResult.Text =" file deleted successfully";
                lblResult.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lblResult.Text =" This file does not exists ";
                lblResult.ForeColor = System.Drawing.Color.Red;
            }
        }       
    }
}

 

Posted 26 days ago Modified on 25 days ago

Hi itsme,

Refer below it's working.

HTML

<asp:GridView runat="server" ID="gvImage" AutoGenerateColumns="false" OnRowCancelingEdit="gvImage_RowCancelingEdit"
    DataKeyNames="Id" OnRowEditing="gvImage_RowEditing" OnRowUpdating="gvImage_RowUpdating"
    OnRowDeleting="gvImage_RowDeleting">
    <Columns>
        <asp:TemplateField HeaderText="Business Name">
            <ItemTemplate>
                <asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_Id" runat="server" Text='<%# Eval("Id") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_name" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Image">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Path") %>' eight="80px"
                    Width="80px" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("Path") %>' Height="80px"
                    Width="80px" /><br />
                <asp:FileUpload ID="FileUpload1" runat="server" />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lbl_edit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                <asp:LinkButton ID="lbl_delete" runat="server" CommandName="Delete">Delete</asp:LinkButton>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="lbl_update" runat="server" CommandName="Update">Update</asp:LinkButton>
                <asp:LinkButton ID="lbl_cancle" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<asp:Label ID="lblResult" runat="server" />

Namespaces

C#

using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;

VB.Net

Imports System.Data.SqlClient
Imports System.IO
Imports System.Data

Code

C#

SqlConnection con;
SqlDataAdapter da;
DataSet ds;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        ImageData();
    }
}

protected void ImageData()
{
    con = new SqlConnection(constr);
    con.Open();
    da = new SqlDataAdapter("SELECT * FROM tblfilespath", con);
    ds = new DataSet();
    da.Fill(ds);
    gvImage.DataSource = ds;
    gvImage.DataBind();
}

protected void gvImage_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvImage.EditIndex = -1;
    ImageData();
}

protected void gvImage_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvImage.EditIndex = e.NewEditIndex;
    ImageData();
}

protected void gvImage_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string Id = gvImage.DataKeys[e.RowIndex].Value.ToString();
    TextBox txt_BName = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_BName");
    TextBox txt_city = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_city");
    TextBox txt_name = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_name");
    TextBox txt_toll = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_toll");
    TextBox txt_link = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_link");
    TextBox txt_pay = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_pay");
    TextBox txt_email = (TextBox)gvImage.Rows[e.RowIndex].FindControl("txt_email");
    FileUpload FileUpload1 = (FileUpload)gvImage.Rows[e.RowIndex].FindControl("FileUpload1");
    con = new SqlConnection(constr);

    string path = "~/uploads/";
    if (FileUpload1.HasFile)
    {
        path += FileUpload1.FileName;
        FileUpload1.SaveAs(MapPath(path));
    }
    else
    {
        Image img = (Image)gvImage.Rows[e.RowIndex].FindControl("img_user");
        path = img.ImageUrl;
    }
    SqlCommand cmd = new SqlCommand("update Q_SP_Afterlogin set Bussiness_name='" + txt_BName.Text + "',city='" + txt_city.Text + "',name='" + txt_name.Text + "',toll_free='" + txt_toll.Text + "',website_link='" + txt_link.Text + "',payment_mode='" + txt_pay.Text + "',email='" + txt_email.Text + "',Images='" + path + "'  where Id=" + Id + "", con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    gvImage.EditIndex = -1;
    ImageData();
}

protected void gvImage_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridViewRow row = (GridViewRow)gvImage.Rows[e.RowIndex];
    Label Id = (Label)row.FindControl("lblId");
    Label name = (Label)row.FindControl("lblname");
    con = new SqlConnection(constr);
    con.Open();
    SqlCommand cmd = new SqlCommand("delete FROM tblfilespath where Id='" + Convert.ToInt32(gvImage.DataKeys[e.RowIndex].Value.ToString()) + "'", con);
    cmd.ExecuteNonQuery();
    con.Close();
    ImageDeleteFromFolder(name.Text);
    ImageData();
}

protected void ImageDeleteFromFolder(string Images)
{
    string file_name = Images;
    string path = Server.MapPath("~/uploads/");
    FileInfo file = new FileInfo(path + file_name);
    if (file.Exists)
    {
        file.Delete();
        lblResult.Text = " file deleted successfully";
        lblResult.ForeColor = System.Drawing.Color.Green;
    }
    else
    {
        lblResult.Text = " This file does not exists ";
        lblResult.ForeColor = System.Drawing.Color.Red;
    }
}

VB.Net

Private con As SqlConnection
Private da As SqlDataAdapter
Private ds As DataSet
Private constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        ImageData()
    End If
End Sub

Protected Sub ImageData()
    con = New SqlConnection(constr)
    con.Open()
    da = New SqlDataAdapter("SELECT * FROM tblfilespath", con)
    ds = New DataSet()
    da.Fill(ds)
    gvImage.DataSource = ds
    gvImage.DataBind()
End Sub

Protected Sub gvImage_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
    gvImage.EditIndex = -1
    ImageData()
End Sub

Protected Sub gvImage_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
    gvImage.EditIndex = e.NewEditIndex
    ImageData()
End Sub

Protected Sub gvImage_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    Dim Id As String = gvImage.DataKeys(e.RowIndex).Value.ToString()
    Dim txt_BName As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_BName"), TextBox)
    Dim txt_city As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_city"), TextBox)
    Dim txt_name As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_name"), TextBox)
    Dim txt_toll As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_toll"), TextBox)
    Dim txt_link As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_link"), TextBox)
    Dim txt_pay As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_pay"), TextBox)
    Dim txt_email As TextBox = CType(gvImage.Rows(e.RowIndex).FindControl("txt_email"), TextBox)
    Dim FileUpload1 As FileUpload = CType(gvImage.Rows(e.RowIndex).FindControl("FileUpload1"), FileUpload)
    con = New SqlConnection(constr)
    Dim path As String = "~/uploads/"

    If FileUpload1.HasFile Then
        path += FileUpload1.FileName
        FileUpload1.SaveAs(MapPath(path))
    Else
        Dim img As Image = CType(gvImage.Rows(e.RowIndex).FindControl("img_user"), Image)
        path = img.ImageUrl
    End If

    Dim cmd As SqlCommand = New SqlCommand("update Q_SP_Afterlogin set Bussiness_name='" & txt_BName.Text & "',city='" + txt_city.Text & "',name='" + txt_name.Text & "',toll_free='" + txt_toll.Text & "',website_link='" + txt_link.Text & "',payment_mode='" + txt_pay.Text & "',email='" + txt_email.Text & "',Images='" & path & "'  where Id=" & Id & "", con)
    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
    gvImage.EditIndex = -1
    ImageData()
End Sub

Protected Sub gvImage_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
    Dim row As GridViewRow = CType(gvImage.Rows(e.RowIndex), GridViewRow)
    Dim Id As Label = CType(row.FindControl("lblId"), Label)
    Dim name As Label = CType(row.FindControl("lblname"), Label)
    con = New SqlConnection(constr)
    con.Open()
    Dim cmd As SqlCommand = New SqlCommand("delete FROM tblfilespath where Id='" & Convert.ToInt32(gvImage.DataKeys(e.RowIndex).Value.ToString()) & "'", con)
    cmd.ExecuteNonQuery()
    con.Close()
    ImageDeleteFromFolder(name.Text)
    ImageData()
End Sub

Protected Sub ImageDeleteFromFolder(ByVal Images As String)
    Dim file_name As String = Images
    Dim path As String = Server.MapPath("~/uploads/")
    Dim file As FileInfo = New FileInfo(path & file_name)

    If file.Exists Then
        file.Delete()
        lblResult.Text = " file deleted successfully"
        lblResult.ForeColor = System.Drawing.Color.Green
    Else
        lblResult.Text = " This file does not exists "
        lblResult.ForeColor = System.Drawing.Color.Red
    End If
End Sub

Screenshot