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

ASP.NET DataGrid 取得資料項各欄位數值完整指南:繫結欄位與模板欄位

     編輯:關於ASP.NET

在 DataGrid 事件處理 (ItemCommand, UpdateCommand 等) 中,常需從觸發行 (e.Item) 取得特定欄位數值。本文整理繫結欄位 (BoundColumn) 與模板欄位 (TemplateColumn) 兩大類型在編輯/非編輯狀態下的取值語法。

1. 繫結欄位 (BoundColumn)

狀態語法說明
非編輯狀態 / 唯讀欄位 e.Item.Cells[索引].Text 直接取 HTML 文字內容
編輯狀態 (渲染為 TextBox) ((TextBox)(e.Item.Cells[索引].Controls[0])).Text Controls[0] 為自動產生的 TextBox

2. 模板欄位 (TemplateColumn)

模板欄位可放置任意控件 (Label, TextBox, CheckBox, DropDownList 等),需知控件 ID 並用 FindControl 取得引用:

// 範例:取得 CheckBox 勾選狀態
bool isChecked = ((CheckBox)(e.Item.Cells[索引].FindControl("cbSex"))).Checked;

// 範例:取得 DropDownList 選中值
string val = ((DropDownList)(e.Item.Cells[索引].FindControl("ddlCategory"))).SelectedValue;

// 範例:取得 TextBox 文字
string txt = ((TextBox)(e.Item.Cells[索引].FindControl("txtName"))).Text;

常見事件參數

除 SelectedIndexChanged 外,大多數事件參數 e 為 DataGridCommandEventArgs,提供 e.Item (觸發行)、e.CommandName、e.CommandArgument。

最佳實踐建議

  • 優先使用 FindControl 而非 Controls[索引],前者對控件順序不敏感、重構更安全。
  • 模板欄位控件建議加上 runat="server" 並給予有意義 ID。
  • 提取邏輯封裝為擴充方法或 Helper,減少事件處理器雜訊。
  • 新專案改用 GridView + RowUpdating 事件參數 e.NewValues 字典,完全避免手動取值。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved