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

ASP.NET GridView 取得當前行索引八大方法完整比較

     編輯:ASP.NET 基礎

核心場景

GridView 操作中頻繁需求:取得使用者點擊行的索引,進而存取該行資料、控制項或執行業務邏輯。本文整理 8 種常見方法並分析適用場景。

前置準備:含 LinkButton 的 TemplateField

<asp:TemplateField HeaderText="操作">
    <ItemTemplate>
        <asp:LinkButton ID="lbtnQianRu" runat="server" 
            CommandName="QianRu" 
            CommandArgument='<%# Eval("Id") %>'>簽入</asp:LinkButton>
        <asp:LinkButton ID="lbtnQianChu" runat="server" 
            CommandName="QianChu">簽出</asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

八大方法完整解析

方法一:CommandSource 父層級遍歷 (RowCommand 事件)

protected void gv_Company_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "QianRu") 
    {
        // 透過 CommandSource 找到 LinkButton -> Parent (Cell) -> Parent (Row)
        GridViewRow drv = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));
        int id = Convert.ToInt32(GridView1.DataKeys[drv.RowIndex].Value);
    }
}
  • 需求:GridView 必須設定 DataKeyNames="Id"
  • 原理:控制項樹層級:LinkButton → DataControlFieldCell → GridViewRow

方法二:NamingContainer 取得行容器 (RowCommand 事件)

GridViewRow drv = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int id = Convert.ToInt32(GridView1.Rows[drv.RowIndex].Cells[0].Text);
  • 優點:NamingContainer 直接回傳實作 INamingContainer 的容器 (GridViewRow)
  • 取值方式:透過 Cells[索引] 取得儲存格文字

方法三:Command 事件 + Sender 遍歷

protected void lbtnQianChu_Command(object sender, CommandEventArgs e) 
{
    LinkButton lb = (LinkButton)sender;
    DataControlFieldCell dcf = (DataControlFieldCell)lb.Parent;
    GridViewRow gvr = (GridViewRow)dcf.Parent;
    lbtnQianChu.SelectedIndex = gvr.RowIndex;
}
  • 事件來源:LinkButton OnCommand 而非 GridView RowCommand
  • 適用:需在按鈕層級處理邏輯時

方法四:Click 事件 + NamingContainer (最簡潔)

protected void LinkButton1_Click(object sender, EventArgs e) 
{
    int row = ((GridViewRow)((LinkButton)sender).NamingContainer).RowIndex;
}
  • 優點:一行程式碼取得行索引
  • 缺點:無法直接取得 CommandArgument,需額外處理

方法五:DropDownList SelectedIndexChanged 事件

DropDownList ddl = (DropDownList)sender;
GridViewRow gvr = (GridViewRow)ddl.NamingContainer;
int id = int.Parse(GridView1.DataKeys[gvr.RowIndex][0].ToString());
int num = int.Parse(ddl.Text);
  • 關鍵:DropDownList 無 CommandName,必須靠 NamingContainer
  • AutoPostBack:必須設定 AutoPostBack="true"

方法六:CheckBox CheckedChanged 事件

CheckBox chk = (CheckBox)sender;
DataControlFieldCell dcf = (DataControlFieldCell)chk.Parent;
GridViewRow gvr = (GridViewRow)dcf.Parent;
  • 同方法三,控制項不同但遍歷邏輯相同

方法七:內嵌運算式直接顯示索引 (無後端程式碼)

<asp:GridView ID="gvTest" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                DisplayIndex : <%# Container.DisplayIndex %> || 
                DataItemIndex : <%# Container.DataItemIndex %><br />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
  • Container.DisplayIndex:顯示索引 (含分頁)
  • Container.DataItemIndex:資料項實際索引 (跨分頁連續)
  • 純前端:無需後端程式碼,適合顯示用途

方法八:RowCreated 預先綁定 CommandArgument

protected void gvInfo_RowCreated(object sender, GridViewRowEventArgs e) 
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {
        LinkButton lk1 = (LinkButton)e.Row.FindControl("lkbtn");
        lk1.CommandArgument = e.Row.RowIndex.ToString(); // 寫入行索引
    }
}

protected void gvInfo_RowCommand(object sender, GridViewCommandEventArgs e) 
{
    if (e.CommandName == "ADD") 
    {
        int index = Convert.ToInt32(e.CommandArgument);
        string aa = gvInfo.Rows[index].Cells[1].Text;
    }
}
  • 策略:在 RowCreated 階段將行索引預存入 CommandArgument
  • 優點:RowCommand 直接取得索引,無需遍歷控制項樹
  • 注意:需確保 LinkButton ID 正確

方法選擇決策表

場景推薦方法理由
RowCommand 事件 + 需 DataKey方法一標準做法,配合 DataKeyNames 最穩健
RowCommand 事件 + 需 Cells 值方法二NamingContainer 語意清晰,效能佳
LinkButton 獨立 Command/Click 事件方法三/四事件綁定靈活,程式碼簡潔
DropDownList/CheckBox 觸發方法五/六無 CommandName 唯一解
純前端顯示索引方法七零後端程式碼,效能最佳
高頻操作 + 追求效能方法八預綁定避免執行時遍歷

NamingContainer 核心機制補充

INamingContainer 介面標記命名容器,確保子控制項 UniqueID 唯一性。GridViewRow 實作此介面,使每行內的同名控制項 (如 "lbtnQianRu") 不會 ID 衝突。Control.NamingContainer 屬性向上尋找最近的命名容器,對 GridView 即為該行的 GridViewRow。

掌握這 8 種方法,能根據具體場景選擇最適合的取得行索引策略,提升開發效率與程式碼品質。

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