namespace CopyLab
{
internal class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable("手動建立資料的 DataTable");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Data", typeof(string));
dt.Rows.Add("1", "原有資料");
dt.Rows.Add("2", "原有資料");
dt.AcceptChanges();
// 刪除第一筆資料
dt.Rows[0].Delete();
// 修改第二筆資料
dt.Rows[1]["Data"] = "更新資料";
// 新增第三筆資料
dt.Rows.Add("3", "新增資料");
ShowData(dt);
DataTable copyDataTable = dt.Copy();
copyDataTable.TableName = "透過 Copy() 產生";
ShowData(copyDataTable);
}
private static void ShowData(DataTable dt)
{
string info = string.Empty;
info = $"Table:{dt.TableName}" + Environment.NewLine;
DataRowVersion version;
foreach (DataRow dr in dt.Rows)
{
version = dr.RowState == DataRowState.Deleted ? DataRowVersion.Original : DataRowVersion.Current;
info += $"ID:{dr["ID", version]} - Data:{dr["Data", version]} - RowState:{dr.RowState}" + Environment.NewLine;
}
Console.WriteLine(info);
}
}
}
驗證結果是會連 DataRow 狀態都複製過去星期四, 10月 16, 2025
[ADO.NET] Copy
之前使用 DataTable.Copy() 時,整個 DataTable 的 DataRow 都是處於 unchange 狀態,剛好遇上資料修改狀態下要使用 DataTable.Copy(),驗證 DataTable.Copy() 會連 DataRow 狀態會一併複製過去
訂閱:
張貼留言 (Atom)

沒有留言:
張貼留言