DataGrid 內建「編輯、更新、取消」按鈕列,配合三大事件 (EditCommand, UpdateCommand, CancelCommand) 即可實現列內編輯。本文詳細說明事件流程、編輯模式切換、數值提取 (唯讀/可編輯欄位) 與更新範例。
| 事件 | 觸發時機 | 核心任務 |
|---|---|---|
EditCommand | 點擊「編輯」 | 設定 EditItemIndex,重新 DataBind() |
CancelCommand | 點擊「取消」 | 設定 EditItemIndex = -1,重新 DataBind() |
UpdateCommand | 點擊「更新」 | 提取新值 → 執行更新 → 設定 EditItemIndex = -1 → 重新 DataBind() |
// 唯讀繫結欄位 (非編輯狀態或 ReadOnly=true) string val = e.Item.Cells[列索引].Text; // 可編輯繫結欄位 (編輯狀態下渲染為 TextBox) string val = ((TextBox)(e.Item.Cells[列索引].Controls[0])).Text;
唯讀欄位通常為主鍵,用於 WHERE 條件;可編輯欄位對應 SET 子句。
private void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
// 主鍵 (唯讀欄位,第 1 欄)
string customerId = e.Item.Cells[1].Text;
// 可編輯欄位 (第 2、3 欄)
string companyName = ((TextBox)(e.Item.Cells[2].Controls[0])).Text;
string city = ((TextBox)(e.Item.Cells[3].Controls[0])).Text;
// 參數化更新 (防 SQL 注入)
string sql = "UPDATE Customers SET CompanyName=@cn, City=@city WHERE CustomerID=@id";
using (var cn = new SqlConnection(connStr))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.AddWithValue("@cn", companyName);
cmd.Parameters.AddWithValue("@city", city);
cmd.Parameters.AddWithValue("@id", customerId);
cn.Open();
cmd.ExecuteNonQuery();
}
DataGrid1.EditItemIndex = -1;
BindDataGrid1();
}
FindControl("控件ID") 取值。