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

GridView CommandField 刪除按鈕加入確認對話框的兩種做法

     編輯:ASP.NET 基礎

前言

GridView 內建 CommandField ShowDeleteButton="True" 產生的刪除按鈕預設無確認機制。本文示範兩種零後端代碼/少量代碼加入確認對話框的標準做法。

做法一:轉為 TemplateField + OnClientClick(設計師操作,零代碼)

  1. 設計檢視 → 右鍵 GridView → 編輯欄位。
  2. 選中 CommandField(顯示為「刪除」) → 點選右側 將此欄位轉換為 TemplateField 連結。
  3. 切換至 原始碼 檢視,找到產生的 <asp:LinkButton>:
<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" runat="server" 
            CausesValidation="False" CommandName="Delete" Text="刪除">
        </asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>
  1. 在 LinkButton 加入 OnClientClick:
<asp:LinkButton ID="LinkButton1" runat="server" 
    CausesValidation="False" CommandName="Delete" Text="刪除"
    OnClientClick="return confirm('確定要刪除嗎?');" />

完成。使用者點擊「刪除」先彈出確認,取消則不回傳,確定才觸發 RowDeleting。

做法二:RowDataBound 動態注入(可依資料行內容調整訊息)

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // 假設刪除按鈕在第 6 格 (索引 6),名稱在第 1 格
        var lnk = e.Row.Cells[6].Controls[0] as LinkButton;
        if (lnk != null && lnk.CommandName == "Delete")
        {
            string name = e.Row.Cells[1].Text;
            string script = $"return confirm('確定要刪除:「{name}」嗎?');";
            lnk.Attributes["onclick"] = script;
        }
    }
}

注意:Cell 索引需與實際 Columns 對應;若使用 AutoGenerateColumns 索引會隨資料變動,建議固定欄位並用 FindControl 更穩健。

後端 RowDeleting 完全不用改

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
    bool ok = BLL.Delete(id);
    // 重新繫結...
}

進階:替換為 SweetAlert2

// 做法一
OnClientClick="return Swal.fire({title:'確定?',icon:'warning',showCancelButton:true}).then(r=>r.isConfirmed);"

// 做法二
lnk.Attributes["onclick"] = $"return Swal.fire({{title:'確定刪除 {name}?',icon:'warning',showCancelButton:true}}).then(r=>r.isConfirmed);";

比較總結

做法優點缺點建議場景
TemplateField + OnClientClick零後端代碼、設計師可視化、效能最佳訊息固定、無法帶入動態資料通用刪除確認
RowDataBound 動態注入訊息可包含資料欄位需維護 Cell 索引、微量後端代碼需顯示刪除項目名稱/ID

結語

預設採用 做法一,簡單、標準、無維護負擔;若專案需求「刪除前顯示項目名稱」,再採 做法二。兩者皆不影響現有 RowDeleting 邏輯,立即可上線。

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