萬盛學電腦網

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

ASP.NET GridView 取得特定行列資料值的正確姿勢 (RowDataBound 事件)

核心概念:RowDataBound 事件

`GridView.RowDataBound` 在**每一行資料繫結完成後**觸發,是存取、修改行內控制項/資料值的最佳時機。事件參數 `GridViewRowEventArgs` 提供 `Row` 屬性取得 `GridViewRow` 物件。

基本存取模式


protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // 1. 過濾資料列 (排除 Header, Footer, Pager 等)
    if (e.Row.RowType != DataControlRowType.DataRow) return;

    // 2. 取得資料物件 (若繫結的是具型別 List)
    var item = (MyEntity)e.Row.DataItem;
    // 或 DataRowView (繫結 DataTable/DataView)
    var drv = (DataRowView)e.Row.DataItem;
    string name = drv["Name"].ToString();

    // 3. 透過 Cells 索引取得儲存格文字 (適用於 BoundField)
    string cellText = e.Row.Cells[0].Text; // 第 1 欄
    // 注意:含 TemplateField 時 Cells 索引會包含控制項,Text 可能為空

    // 4. 透過 FindControl 取得 TemplateField 內的控制項 (推薦)
    var lblName = (Label)e.Row.FindControl("lblName");
    var btnEdit = (Button)e.Row.FindControl("btnEdit");
    if (lblName != null) lblName.Text = "★ " + lblName.Text;
}

三種欄位類型的取值差異

欄位類型Cells[index].TextFindControl(ID)DataItem 屬性
BoundField✅ 直接取得文字❌ 無控制項✅ 強型別轉換最佳
TemplateField (Label)❌ 空白或  ✅ 取得 Label 控制項✅
TemplateField (TextBox)❌✅ 取得 TextBox 讀取/修改 .Text✅
CommandField / ButtonField❌✅ 取得 Button/LinkButton✅
CheckBoxField❌✅ 取得 CheckBox (Checked 屬性)✅

實戰範例:根據資料值動態調整樣式/啟用狀態


protected void gvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.DataRow) return;

    var order = (Order)e.Row.DataItem;

    // 1. 根據狀態顏色標記整列
    switch (order.Status)
    {
        case OrderStatus.Cancelled:
            e.Row.CssClass = "text-danger text-decoration-line-through";
            break;
        case OrderStatus.Pending:
            e.Row.CssClass = "text-warning";
            break;
        case OrderStatus.Completed:
            e.Row.CssClass = "text-success";
            break;
    }

    // 2. 禁用已完成訂單的「取消」按鈕
    var btnCancel = (Button)e.Row.FindControl("btnCancel");
    if (btnCancel != null && order.Status == OrderStatus.Completed)
    {
        btnCancel.Enabled = false;
        btnCancel.ToolTip = "已完成訂單無法取消";
    }

    // 3. 格式化金額顯示 (TemplateField 中的 Label)
    var lblAmount = (Label)e.Row.FindControl("lblAmount");
    if (lblAmount != null)
    {
        lblAmount.Text = order.Amount.ToString("C", CultureInfo.GetCultureInfo("zh-TW"));
    }

    // 4. 資料綁定下拉選單 (編輯模式專用)
    if ((e.Row.RowState & DataControlRowState.Edit) > 0)
    {
        var ddlStatus = (DropDownList)e.Row.FindControl("ddlStatus");
        if (ddlStatus != null)
        {
            ddlStatus.DataSource = Enum.GetValues(typeof(OrderStatus));
            ddlStatus.DataBind();
            ddlStatus.SelectedValue = order.Status.ToString();
        }
    }
}

進階技巧

1. 取得 DataKey (主鍵值)


int id = (int)gvData.DataKeys[e.Row.RowIndex].Value; // 需設定 DataKeyNames="Id"
// 或複合鍵
var keys = gvData.DataKeys[e.Row.RowIndex].Values; // Dictionary

2. RowDataBound vs RowCreated

| 事件 | 觸發時機 | DataItem 可用 | 適用場景 | |------|----------|---------------|----------| | RowCreated | 建立 Row 控制項樹時 | ❌ | 動態加入控制項、設定靜態屬性 | | RowDataBound | 資料繫結完成後 | ✅ | 讀取/修改資料值、動態樣式、條件顯示 |

3. 效能優化:避免在 RowDataBound 重複查詢資料庫


// ❌ 錯誤:每行觸發查詢 → N+1 問題
protected void gv_RowDataBound(...) {
    var detail = db.Details.Find(id); // 災難!
}

// ✅ 正確:預先載入所有相關資料到 Dictionary/List
var details = db.Details.Where(d => ids.Contains(d.OrderId)).ToDictionary(d => d.OrderId);
protected void gv_RowDataBound(...) {
    if (details.TryGetValue(id, out var detail)) { /* 使用 detail */ }
}

4. 巢狀 GridView / Repeater 內層繫結



    
        
            
                
                    
                
            
        
    


protected void gvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var master = (MasterEntity)e.Row.DataItem;
        var gvDetail = (GridView)e.Row.FindControl("gvDetail");
        gvDetail.DataSource = master.Details; // 或從 Dictionary 取得
        gvDetail.DataBind();
    }
}

常見錯誤與除錯

  • NullReferenceException:`FindControl` 回傳 null → 檢查 ID 拼寫、確認 TemplateField 正確、RowState 是否 Edit/Insert。
  • Cells 索引錯誤:自動產生欄位時索引會隨欄位順序改變 → 改用 `DataKeyNames` + `DataItem` 強型別存取。
  • 事件未綁定:GridView 標記缺少 `OnRowDataBound="gv_RowDataBound"` 或程式碼未 `gv.RowDataBound += ...`。
  • ViewState 膨脹:大量 TemplateField 控制項會增加 ViewState → 關閉不需要的 ViewState、改用 `EnableViewState="false"`。

善用 `RowDataBound` + `DataItem` 強型別轉換 + `FindControl` 精準定位控制項,是掌控 GridView 顯示邏輯的關鍵。現代開發建議轉向 **ListView/Repeater + 前端框架** 或 **Blazor/Razor Components** 獲得更清晰的資料綁定模型。

copyright © 萬盛學電腦網 all rights reserved