`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].Text | FindControl(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();
}
}
}
int id = (int)gvData.DataKeys[e.Row.RowIndex].Value; // 需設定 DataKeyNames="Id"
// 或複合鍵
var keys = gvData.DataKeys[e.Row.RowIndex].Values; // Dictionary
// ❌ 錯誤:每行觸發查詢 → 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 */ }
}
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();
}
}
善用 `RowDataBound` + `DataItem` 強型別轉換 + `FindControl` 精準定位控制項,是掌控 GridView 顯示邏輯的關鍵。現代開發建議轉向 **ListView/Repeater + 前端框架** 或 **Blazor/Razor Components** 獲得更清晰的資料綁定模型。