GridView按钮事件

时间:2016-01-03 15:08:17

标签: asp.net ms-access

我构建GridView,显示我网站中的所有图像。图像位于" img"文件夹中。我添加了一个名为" DeleteButton"的按钮。并且他做了事件(CommandName)" DeleteImg"。 我有这个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>
&#13;
&#13;
&#13;

我有这个方法:

    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.
    }
}

我想要字符串&#34; imgname&#34;值将是DataField&#34; ImgName&#34;对于所有行。 我怎么能这样做?

1 个答案:

答案 0 :(得分: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.
}