2017-08-17 121 views
1

我通过从文件夹中获取图像来显示DataList中的一些图像。现在,我想在我的Datalist中单击“删除”按钮时删除文件夹中的图像。使用数据列表从文件夹中删除图像

我的问题是,我无法从中获取文件名:

string fileName = e.CommandArgument.ToString(); 

我尝试了几种解决方案,但没有得到正确的解决方案。

HTML标记:

<asp:DataList OnDeleteCommand="gvImages_DeleteCommand" ID="gvImages" RepeatColumns="5" 
       RepeatDirection="Horizontal" GridLines="Horizontal" runat="server" 
       BorderColor="#336699" BorderStyle="Solid" ShowHeader="true"> 
    <ItemTemplate> 
    <center> 
     <table> 
      <tr> 
       <td style="width: 90px; height: 90px"> 
        <img id="PICID" runat="server" src='<%# Container.DataItem %>' alt='' 
         style="height: 100px; width: 100px;" /><br /> 
        <asp:Button ID="Delete" Height="22px" CommandName="Delete" 
           Width="100px" runat="server" Text="Delete Picture" /><br /> 
       </td> 
      </tr> 
     </table> 
    </center> 
    </ItemTemplate> 
</asp:DataList> 

代码隐藏:

protected void gvImages_DeleteCommand(object source, DataListCommandEventArgs e) 
{ 
    //you can hold filename on Button's CommandArgument 

    string fileName = e.CommandArgument.ToString(); 

    // here i can not get the file name to delete it from the folder 

    File.Delete(Server.MapPath(fileName)); 

    FileInfo fInfo; 

    fInfo = new FileInfo(fileName); 

    fInfo.Delete(); 

    gvImages.DataBind(); 
} 
+0

是'使用Server.Mappath(文件名)'返回正确路径?你也获得任何权限例外吗? –

回答

0

你必须在你的DataList控件添加asp:Image控制和尝试:

HTML标记:FilePath是一个柱子在您的数据源名称。

<asp:Image ID="PICID" runat="server" 
      ImageUrl='<%# DataBinder.Eval(Container.DataItem, "FilePath") %>' /> 

代码隐藏:gvImages_DeleteCommand事件,如:

string url = ((Image)gvImages.Items[e.Item.ItemIdex].FindControl("PICID")).ImageUrl; 

string path = Server.MapPath(url); 

if (File.Exists(path)) 
{ 
    File.Delete(path); // deletes file from folder 
} 
相关问题