系列第四篇:詳細說明 `DataRow` 的刪除、移除、狀態枚舉 (`RowState`) 以及如何檢查掛起變更 (Current/Original 版本)。
| 方法 | 行為 | 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);
| 值 | 意義 |
|---|---|
| Unchanged | 載入後未修改 / `AcceptChanges()` 後 |
| Added | `NewRow()` + `Rows.Add()` 後 |
| Modified | 欄位值被修改後 |
| Deleted | `Delete()` 後 |
| Detached | 新建未加入集合 / `Remove()` 後 |
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() 取消