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

ASP.NET 2.0 GridView CheckBox 批次刪除完整範例

     編輯:關於ASP.NET

結合「全選 CheckBox」、「列表 CheckBox」與「刪除按鈕」,實現多筆記錄批次刪除。

前端頁面結構

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="DB1_1,DB1_2" AllowPaging="True" AllowSorting="True"
    OnRowDeleting="GridView1_RowDeleting" OnPageIndexChanging="GridView1_PageIndexChanging"
    OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting">
    <Columns>
        <asp:TemplateField HeaderText="序號">
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 + (GridView1.PageIndex * GridView1.PageSize) %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="選擇">
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="操作" ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete"
                    Text="刪除" OnClientClick="return confirm('確認要刪除嗎?');" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<asp:CheckBox ID="chkSelectAll" runat="server" Text="全部選中"
    AutoPostBack="True" OnCheckedChanged="chkSelectAll_CheckedChanged" />
<asp:Button ID="btnDelete" runat="server" Text="刪除" OnClick="btnDelete_Click" />

後端程式碼

protected void btnDelete_Click(object sender, EventArgs e)
{
    string condition = "";
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("chkSelect");
        if (chk.Checked)
        {
            // 假設主鍵為 DB1_1,且序號對應主鍵值
            Label lbl = (Label)GridView1.Rows[i].FindControl("labXH");
            condition = "DB1_1=" + lbl.Text;
            // 實際應用建議使用參數化 SQL 或 ORM
            conn.RunSql("DELETE FROM DB1 WHERE " + condition);
        }
    }
    chkSelectAll.Checked = false;
    GridViewBind(); // 重新繫結
}

protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)row.FindControl("chkSelect");
        chk.Checked = chkSelectAll.Checked;
    }
}

注意事項

  • 範例為示範邏輯,實際專案請務必使用參數化查詢防止 SQL Injection。
  • 分頁情況下僅處理當前頁面勾選項目;跨頁批次刪除需儲存勾選狀態至 ViewState 或 Session。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved