0

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.

  • You're sending `<%# DataBinder.Eval(Container.DataItem,"ID") %>` as the CommandArgument, then taking that CommandArgument in DeleteFile() and you call it filePath... filePath will contain the data that is bound as "ID" where it should be passed the actual file's path... can you provide that as the CommandArgument? – peyote boy Jul 28 '16 at 20:04
  • If you can provide the File's Path the same way you provide `<%# DataBinder.Eval(Container.DataItem,"ID") %>`... perhaps something like `<%# DataBinder.Eval(Container.DataItem,"FilePath") %>` then you're there – peyote boy Jul 28 '16 at 20:06
  • I have tried "filePath" ...I got this error msg: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'filePath'. – Liberty Crown Infotech Jul 29 '16 at 17:15

1 Answers1

0

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>