GridView 內建 CommandName="Select" 選擇功能在部署至伺服器時異常(顯示 "select" 文字而非預期內容),改用 TemplateField 實現選擇按鈕時,RowCommand 事件中無法直接透過 e.CommandArgument 取得行索引,需替代方案。
在 LinkButton 標籤中使用內嵌運算式綁定 Container 的 RowIndex。
<asp:LinkButton ID="btnSelect" runat="server" CausesValidation="False"
CommandName="Select" Text="選擇"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>">
</asp:LinkButton>
後端取得:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
int rowIndex = Convert.ToInt32(e.CommandArgument);
// 使用 rowIndex 存取資料源...
}
}
不設定 CommandArgument,在後端由觸發事件的控件(e.CommandSource)向上兩層找到 GridViewRow。
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
GridViewRow gvRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
// 或寫:((LinkButton)e.CommandSource).Parent.Parent
int rowIndex = gvRow.RowIndex;
// 使用 rowIndex...
}
}
| 維度 | 方法一 CommandArgument | 方法二 NamingContainer |
|---|---|---|
| 優點 | 直觀、前端宣告式、不依賴控件階層 | 前端標籤較乾淨、不需內嵌運算式 |
| 缺點 | 需正確轉型 Container、舊版 VS 智能提示較弱 | 依賴控件父層結構,若模板巢狀變動易失效 |
| 適用場景 | 簡單模板、行索引即為所需 | 已有複雜模板、不想修改前端標籤 |
若 GridView 設定 DataKeyNames="ID",最直接的是:
int rowIndex = ...; // 任一方法取得
string id = gv.DataKeys[rowIndex].Value.ToString();
GridView TemplateField 實現選擇功能時,取得行索引有「前端綁定 CommandArgument」與「後端追溯 NamingContainer」兩種主流做法。建議優先使用方法一(宣告式、穩健),搭配 DataKeys 取得主鍵值進行後續業務處理。