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

C# DataSet 與 DataTable 深度解析 (四) - DataRow 刪除、清除、狀態與掛起變更

     編輯:關於C語言

系列第四篇:詳細說明 `DataRow` 的刪除、移除、狀態枚舉 (`RowState`) 以及如何檢查掛起變更 (Current/Original 版本)。

刪除 vs 移除

方法行為RowState資料庫同步
`row.Delete()`標記為刪除,保留於 `Rows` 集合`Deleted``DataAdapter.Update` 時發送 `DELETE` SQL
`table.Rows.Remove(row)`從集合**永久移除**`Detached`**不會**同步至資料庫
`table.Rows.RemoveAt(index)`同上`Detached`同上

// 標記刪除 (可回滾、可同步 DB)
DataRow row = ds.Tables["Customers"].Rows.Find("ALFKI");
row.Delete();

// 永久移除 (僅記憶體)
ds.Tables["Customers"].Rows.Remove(row);
// 或
ds.Tables["Customers"].RemoveAt(index);

RowState 枚舉值

值意義
Unchanged載入後未修改 / `AcceptChanges()` 後
Added`NewRow()` + `Rows.Add()` 後
Modified欄位值被修改後
Deleted`Delete()` 後
Detached新建未加入集合 / `Remove()` 後

RowState 變化示範


var table = new DataTable();
table.Columns.Add("Name");
var row = table.NewRow();           // Detached
Console.WriteLine(row.RowState);    // Detached

table.Rows.Add(row);                // Added
Console.WriteLine(row.RowState);    // Added

table.AcceptChanges();              // Unchanged
Console.WriteLine(row.RowState);    // Unchanged

row["Name"] = "Scott";              // Modified
Console.WriteLine(row.RowState);    // Modified

row.Delete();                       // Deleted
Console.WriteLine(row.RowState);    // Deleted

掛起變更版本存取

`DataRow` 維護三個版本:`Current` (最新)、`Original` (`AcceptChanges` 時的快照)、`Proposed` (`BeginEdit`/`EndEdit` 間)。


row["CompanyName"] = "NewCo"; // Modified
Console.WriteLine(row["CompanyName", DataRowVersion.Current]); // NewCo
Console.WriteLine(row["CompanyName", DataRowVersion.Original]); // 原值

編輯緩衝區


row.BeginEdit();
row["CompanyName"] = "NewCo";
row["ContactName"] = "NewContact";
row.EndEdit(); // 或 row.CancelEdit() 取消
  • `BeginEdit`:暫停驗證/事件,允許暫時違反約束。
  • `EndEdit`:提交緩衝變更,觸發 `ColumnChanging`/`ColumnChanged`。
  • `CancelEdit`:捨棄緩衝,還原為 `Current` 版本。

實務建議

  • 批次修改多欄位時務必用 `BeginEdit`/`EndEdit` 包裹,減少事件觸發與驗證開銷。
  • 刪除後若需撤銷:`row.RejectChanges()` (還原為 `Unchanged`)。
  • `HasErrors` / `RowError` / `GetColumnError`:驗證失敗時設定,`DataAdapter.Update` 會檢查並可選擇 `ContinueUpdateOnError`。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved