萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET GridView 透過 sender.Parent 快速取得當前行:CheckBox 觸發範例

情境

在 `GridView` 的 `TemplateField` 中放置 `CheckBox`,當使用者勾選/取消時,需即時更新同一行其他欄位 (如狀態 `Label`) 的顯示。傳統做法需透過 `RowCommand`、`DataKeys` 或迴圈尋找,實則可利用事件來源 `sender` 的父層關係直接定位 `GridViewRow`,程式碼極簡潔。

前端標記

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="ID" />
        <asp:BoundField DataField="Name" HeaderText="名稱" />
        <asp:TemplateField HeaderText="狀態">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Status") %>' />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="選取">
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" 
                    OnCheckedChanged="CheckBox1_CheckedChanged" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

後端事件處理

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
    // 1. 取得觸發事件的 CheckBox
    CheckBox chk = (CheckBox)sender;

    // 2. 向上兩層:CheckBox → DataControlFieldCell (TD) → GridViewRow (TR)
    DataControlFieldCell cell = (DataControlFieldCell)chk.Parent;
    GridViewRow row = (GridViewRow)cell.Parent;

    // 3. 透過 Row 索引或 Cells 找到同行其他控制項
    Label lbl = (Label)row.Cells[2].FindControl("Label1"); // 第 3 欄 (索引 2)

    // 4. 更新狀態
    lbl.Text = chk.Checked ? "T" : "";
}

父層關係圖解

GridViewRow (TR)
 └─ DataControlFieldCell (TD)  ← CheckBox.Parent
      └─ CheckBox
 ┌─ DataControlFieldCell (TD)  ← Label 所在 Cell
 │   └─ Label
 └─ ...

關鍵點總結

  • AutoPostBack="true":CheckBox 必須設定自動回傳才會觸發伺服器端事件。
  • sender → Parent → Parent:`CheckBox` → `DataControlFieldCell` (TableCell) → `GridViewRow`。此關係在 `TemplateField` 中固定,不受欄位順序影響。
  • FindControl 安全性:`row.Cells[index].FindControl("ID")` 需確認索引正確;更穩健做法是 `row.FindControl("Label1")` 直接搜尋整行 (遞迴)。
  • 適用範圍:任何放在 `TemplateField` / `BoundField` 內、具備 `AutoPostBack` 的控制項 (`DropDownList`、`TextBox`、`Button` 等) 均可用此技巧取得所在行。

替代方案比較

方法優點缺點
sender.Parent.Parent 程式碼最少、無需額外屬性設定、效能最好 依賴控制項層級結構,若未來 GridView 渲染模式變更可能失效 (極少見)
DataKeyNames + RowCommand 官方標準模式、語意清晰、支援分頁/排序後正確索引 需設定 DataKeyNames、CommandName/Argument、在 RowCommand 中判斷、程式碼較多
RowDataBound 綁定 RowIndex 到控制項屬性 不依賴父層結構 需額外儲存 RowIndex (ViewState/Control 屬性)、增加複雜度

現代化建議

  • 若專案允許,改用 **UpdatePanel** 包裹 GridView 實現局部更新,避免整頁閃爍。
  • 前端框架 (Vue/React/Blazor) 管理狀態,僅透過 API 與後端交換資料,徹底移除 ViewState 與 PostBack 機制。

總結

利用 `sender.Parent.Parent` (或 `NamingContainer`) 從事件來源控制項快速定位 `GridViewRow`,是 Web Forms 時代處理 `TemplateField` 內控制項事件最高效、最直觀的技巧。理解控制項樹狀結構 (`Control → NamingContainer → Row`),能靈活應對各種行級操作需求。

copyright © 萬盛學電腦網 all rights reserved