首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 資料教程 65:批次刪除實作-GridView CheckBox 列、刪除按鈕、事務包裝多筆刪除

     編輯:關於ASP.NET

前言

參考 Webmail 介面:每列 CheckBox + 「刪除選取項目」按鈕。本文整合前幾章成果:CheckBoxField (第 52 章) + 事務刪除方法 (第 63 章) 實作批次刪除。

步驟 1:複製現有 CheckBoxField 頁面

  1. 開啟 BatchDelete.aspx 與 EnhancedGridView/CheckBoxField.aspx。
  2. 複製 <asp:Content> 內完整宣告代碼至 BatchDelete.aspx。
  3. 複製後台代碼屬性與方法。

步驟 2:新增批次刪除按鈕與邏輯

<asp:Button ID="btnDeleteSelected" Text="刪除選取產品" 
    OnClick="btnDeleteSelected_Click" />
protected void btnDeleteSelected_Click(object sender, EventArgs e)
{
    List<int> productIDs = new List<int>();
    foreach (GridViewRow row in gvProducts.Rows)
    {
        CheckBox cb = row.FindControl("chkSelect") as CheckBox;
        if (cb != null && cb.Checked)
        {
            int productID = Convert.ToInt32(gvProducts.DataKeys[row.RowIndex].Value);
            productIDs.Add(productID);
        }
    }
    if (productIDs.Count > 0)
    {
        // 呼叫 BLL 事務刪除方法 (第 63 章建立)
        ProductsBLL.DeleteProductsWithTransaction(productIDs);
        // 重新繫結
        gvProducts.DataBind();
    }
}

BLL 事務刪除方法回顧

public static void DeleteProductsWithTransaction(List<int> productIDs)
{
    using (TransactionScope scope = new TransactionScope())
    {
        foreach (int id in productIDs)
            ProductsBLL.DeleteProduct(id); // 內部使用 TableAdapter Delete
        scope.Complete();
    }
}

結語

批次刪除核心在於:CheckBox 列蒐集主鍵 → 事務包裝逐筆刪除 → 重新繫結。模組化設計讓 CheckBoxField、事務刪除方法可獨立復用於其他頁面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved