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

GridView RowCommand 取得行索引三大絕招:CommandSource、CommandArgument、NamingContainer

     編輯:ASP.NET 基礎

背景

GridViewCommandEventArgs 不像 DataGridCommandEventArgs 直接提供 Item 屬性,需自行取得觸發行。

方法一:透過 CommandSource 爬視覺樹(最通用)


var btn = (Button)e.CommandSource;
var row = (GridViewRow)btn.NamingContainer; // 直接取得命名容器(即 GridViewRow)
int rowIndex = row.RowIndex;

原理:NamingContainer 指向實作 INamingContainer 的最近祖先,GridViewRow 即實作此介面。

方法二:RowDataBound 預先綁定 CommandArgument(效能最佳)

前台


<asp:TemplateField>
    <ItemTemplate>
        <asp:Button CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="編輯" />
    </ItemTemplate>
</asp:TemplateField>

後台


int rowIndex = Convert.ToInt32(e.CommandArgument);
var row = GridView1.Rows[rowIndex];

無需爬樹,直接取得索引,適合高頻操作。

方法三:ButtonField 內建支援


<asp:ButtonField CommandName="Delete" ButtonType="Button" Text="刪除" />

ButtonField 會自動將行索引放入 e.CommandArgument,直接轉換即可:


int rowIndex = Convert.ToInt32(e.CommandArgument);
var row = GridView1.Rows[rowIndex];

注意:ButtonField 的 CommandSource 是 GridView 本身,不可用方法一。

綜合範例:統一處理多種命令來源


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
    GridViewRow row = null;
    int rowIndex = -1;

    switch (e.CommandName) {
        case "Edit":   // TemplateField + CommandArgument
            rowIndex = Convert.ToInt32(e.CommandArgument);
            row = GridView1.Rows[rowIndex];
            break;
        case "View":   // TemplateField + NamingContainer
            row = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            break;
        case "Delete": // ButtonField
            rowIndex = Convert.ToInt32(e.CommandArgument);
            row = GridView1.Rows[rowIndex];
            break;
    }

    if (row != null) {
        string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
        // 業務邏輯...
    }
}

選擇指南

情境推薦方法理由
TemplateField 按鈕方法二效能最好,無視覺樹依賴
TemplateField 但不想設 CommandArgument方法一通用、零前台修改
ButtonField方法三內建支援,最省事

避坑提醒

  • 分頁情況下 RowIndex 為頁內索引,配合 DataKeys 取得真實主鍵。
  • NamingContainer 在巢狀控件(如 GridView 在 Repeater 中)可能指向錯誤層級,優先用 CommandArgument。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved