2016-01-03 104 views
0

我构建了GridView,显示我的站点中的所有图像。这些图像位于“img”文件夹中。我添加了一些名为“DeleteButton”的按钮,并执行事件(CommandName)“DeleteImg”。 我有这样的GridView:GridView按钮事件

<asp:GridView ID="GridViewImg" runat="server" DataKeyNames="ImgName" AutoGenerateColumns="False" DataSourceID="AccessDataSource1" 
 
    AllowPaging="True" OnRowCommand="GridViewImg_RowCommand"> 
 
          <Columns> 
 
           <asp:BoundField DataField="ImgName" HeaderText="Image Name" SortExpression="ImgName" /> 
 
           <asp:BoundField DataField="AddDate" HeaderText="Date" SortExpression="AddDate" />          
 
       <asp:TemplateField> 
 
       <ItemTemplate> 
 
    <asp:Button ID="DeleteButton" runat="server" 
 
     CommandName="DeleteImg" 
 
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 
 
     Text="Delete" /> 
 
    </ItemTemplate> 
 
</asp:TemplateField> 
 
          </Columns> 
 
    
 
         </asp:GridView> 
 
         
 
         <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/DB.mdb"  
 
          SelectCommand="SELECT [ImgName], [AddDate] FROM [tbImg] ORDER BY [ImgID] DESC"> 
 
         </asp:AccessDataSource>

,我有这个方法:

protected void GridViewImg_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "DeleteImg") 
    { 
     // Retrieve the row index stored in the 
     // CommandArgument property. 
     int index = Convert.ToInt32(e.CommandArgument); 

     // Retrieve the row that contains the button 
     // from the Rows collection. 
     GridViewRow row = GridViewImg.Rows[index]; 
     string path = HttpContext.Current.Server.MapPath(@"../img"); 
     string imgname=""; 
     System.IO.File.Delete(path + "/"+imgname); 
     // Add code here to add the item to the shopping cart. 
    } 
} 

我想,字符串 “imgname” 值将是数据字段 “ImgName” 所有行。 我该怎么做?

回答

0

这样做:

if (e.CommandName == "DeleteImg") 
{ 
    // Retrieve the row index stored in the 
    // CommandArgument property. 

    int index = Convert.ToInt32(e.CommandArgument); 
    var imgname = GridViewImg.Rows[index].Cells[0].Text; 

    string path = HttpContext.Current.Server.MapPath(@"../img"); 

    System.IO.File.Delete(path + "/"+imgname); 
    // Add code here to add the item to the shopping cart. 
}