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

ASP.NET GridView 模板列實現選擇行功能兩種取得行索引方法

     編輯:ASP.NET 基礎

問題背景

GridView 內建 CommandName="Select" 選擇功能在部署至伺服器時異常(顯示 "select" 文字而非預期內容),改用 TemplateField 實現選擇按鈕時,RowCommand 事件中無法直接透過 e.CommandArgument 取得行索引,需替代方案。

方法一:CommandArgument 綁定 RowIndex

在 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 存取資料源...
    }
}

方法二:透過 CommandSource 追溯 NamingContainer

不設定 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 取得主鍵值進行後續業務處理。

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