在 `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
└─ ...
| 方法 | 優點 | 缺點 |
|---|---|---|
| sender.Parent.Parent | 程式碼最少、無需額外屬性設定、效能最好 | 依賴控制項層級結構,若未來 GridView 渲染模式變更可能失效 (極少見) |
| DataKeyNames + RowCommand | 官方標準模式、語意清晰、支援分頁/排序後正確索引 | 需設定 DataKeyNames、CommandName/Argument、在 RowCommand 中判斷、程式碼較多 |
| RowDataBound 綁定 RowIndex 到控制項屬性 | 不依賴父層結構 | 需額外儲存 RowIndex (ViewState/Control 屬性)、增加複雜度 |
利用 `sender.Parent.Parent` (或 `NamingContainer`) 從事件來源控制項快速定位 `GridViewRow`,是 Web Forms 時代處理 `TemplateField` 內控制項事件最高效、最直觀的技巧。理解控制項樹狀結構 (`Control → NamingContainer → Row`),能靈活應對各種行級操作需求。