asp.netgridviewasplinkbutton

Simultaneously deleting a file from a DataBase and a Folder using a LinkButton or Gridview_RowDeleting method


HELP! Is it achievable to use LinkButton or Gridview_RowDeleting method to simultaneously delete a file from a DataBase and from a Folder? Below is my code using a LinkButton:

<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID = "lnkDelete" Text = "Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" CommandArgument = '<%# DataBinder.Eval(Container.DataItem,"ID") %>' runat = "server" OnClick = "DeleteFile" />
</ItemTemplate>
 </asp:TemplateField>

Code Behind:

protected void grdProducts_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //Get seleted row
        GridViewRow row = grdProducts.Rows[e.NewEditIndex];

        //Get Id of selected product
        int rowId = Convert.ToInt32(row.Cells[1].Text);

        //Redirect user to Manage Products along with the selected rowId
        Response.Redirect("~/Pages/Management/ManageProducts.aspx?id=" + rowId);
    }

    protected void DeleteFile(object sender, EventArgs e)

    {

        string filePath = (sender as LinkButton).CommandArgument;
        File.Delete(filePath);
        Response.Redirect(Request.Url.AbsoluteUri);


    }

PL: I have an existing gridview and a datasource for my table.


Solution

  • Thank you all for your contribution. I later got the answer to this. I will like to share it with all. Just enable OnRowDeleting in your Gridview properties then use the code behind below.

        protected void grdProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
    
        {
            Image oImg = grdProducts.Rows[e.RowIndex].FindControl("ImageFile") as Image;
            if (oImg != null)
            {
                string sUrl = oImg.ImageUrl;
    
                File.Delete(Server.MapPath(sUrl));
    
                grdProducts.DataBind();
            }
        }
    }
    

    Finally: put this TemplateField on your aspx page.

       <asp:TemplateField>
        <ItemTemplate>
          <asp:Image ID="ImageFile" runat="server" ImageUrl='<%# Bind("Image", "Images/Products/{0}")%>'  AlternateText="Picture unavailable"  style="width:50px; height:40px"  />                     
        </ItemTemplate>
        </asp:TemplateField>