萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 利用 NamingContainer 取得 GridView 資料列索引

問題情境

在 GridView 模板欄位放置 DropDownList 並啟用 AutoPostBack,當 SelectedIndexChanged 觸發時,需要取得該控制項所在的資料列索引以進一步處理該列資料。

關鍵屬性:NamingContainer

取得伺服器控制項命名容器的參考,此容器建立唯一命名空間,以區分具有相同 Control.ID 的控制項。實作 INamingContainer 介面的控制項(如 GridViewRow、RepeaterItem)即為命名容器。

解決程式碼

protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList ddl = (DropDownList)sender;
    // 取得包含該 DropDownList 的 GridViewRow
    GridViewRow row = (GridViewRow)ddl.NamingContainer;

    // 取得資料鍵值
    int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);

    // 取得下拉選單選取的值
    int qty = int.Parse(ddl.SelectedValue);

    // 後續業務邏輯...
}

為何有效?

  • DropDownList 位於 GridViewRow 的控制項樹狀結構中。
  • GridViewRow 實作 INamingContainer,故為 DropDownList 的 NamingContainer。
  • 透過 RowIndex 即可對應到資料來源中的正確列。

適用範圍

同樣適用於 Repeater、DataList、ListView 等重複性資料控制項中的任何觸發 PostBack 之子控制項(Button、CheckBox、LinkButton 等)。

copyright © 萬盛學電腦網 all rights reserved