更新新 DataRow 中的值也会影响它来自的 DataTable 吗?
Updating values in a new DataRow also affects the DataTable where it's from?
这是我的第一个问题,
找遍了也没找到答案
如果有任何帮助,我将不胜感激。
假设我有一个名为 dtTest
的数据表,如下所示
+----+------+
| id | name |
+----+------+
| 1 | AA |
| 2 | BB |
+----+------+
当我从 dtTest
创建一个新的 DataRow 并更新它的值时
DataRow drTest = dtTest.Rows[0];
drTest["name"] = "CC";
我认为我唯一改变的是新对象中的值 drTest
,
它独立于 dtTest
,
但 dtTest
实际上也受到了影响。
+----+------+
| id | name |
+----+------+
| 1 | CC |
| 2 | BB |
+----+------+
为什么这个动作会影响原来的DataTable?
这不会创建新行,而只是对 table 中第一行的引用:
DataRow drTest = dtTest.Rows[0]; // Rows is a DataRowCollection which contains all table-rows
如果您想要一个新行,您有以下选项:
DataRow drTest1 = dtTest.NewRow(); // not yet added, you need: dtTest.Rows.Add(drTest1);
DataRow drTest2 = dtTest.Rows.Add(); // already added without values
DataRow drTest3 = dtTest.Rows.Add(1, "test"); // already added with values
drTest
是您的 dtTest
table 的行对象。因此,对 drtest
的任何更改都会影响您的数据table dtTest
如果你想要一个新行:
DataRow drTest1 = dtTest.NewRow();
dtTest["ID"] = 3;
dtTest["name"] = "CC;
这是我的第一个问题,
找遍了也没找到答案
如果有任何帮助,我将不胜感激。
假设我有一个名为 dtTest
的数据表,如下所示
+----+------+
| id | name |
+----+------+
| 1 | AA |
| 2 | BB |
+----+------+
当我从 dtTest
创建一个新的 DataRow 并更新它的值时
DataRow drTest = dtTest.Rows[0];
drTest["name"] = "CC";
我认为我唯一改变的是新对象中的值 drTest
,
它独立于 dtTest
,
但 dtTest
实际上也受到了影响。
+----+------+
| id | name |
+----+------+
| 1 | CC |
| 2 | BB |
+----+------+
为什么这个动作会影响原来的DataTable?
这不会创建新行,而只是对 table 中第一行的引用:
DataRow drTest = dtTest.Rows[0]; // Rows is a DataRowCollection which contains all table-rows
如果您想要一个新行,您有以下选项:
DataRow drTest1 = dtTest.NewRow(); // not yet added, you need: dtTest.Rows.Add(drTest1);
DataRow drTest2 = dtTest.Rows.Add(); // already added without values
DataRow drTest3 = dtTest.Rows.Add(1, "test"); // already added with values
drTest
是您的 dtTest
table 的行对象。因此,对 drtest
的任何更改都会影响您的数据table dtTest
如果你想要一个新行:
DataRow drTest1 = dtTest.NewRow();
dtTest["ID"] = 3;
dtTest["name"] = "CC;