【问题标题】:Why duplicate records when copying a row from a datatable to another为什么将行从数据表复制到另一个时重复记录
【发布时间】:2019-07-02 06:45:12
【问题描述】:

我正在尝试将列上的所有行从一个数据表复制到另一个数据表。这样做时,记录会重复。

这就是我正在做的:

foreach(DataRow dtTP in sltsrcTfobs.Rows) {
    DataRow destRow = dtTPositions.NewRow();
    destRow["SystemOrdinal"] = dtTP["PosID"];
    dtTPositions.Rows.Add(destRow);
}

此列只有 int 值。例如,目前它有 10 行,值为 1、2、3、4、5、6、7、8、9、10。当我将行复制到新数据表“dtTPositions”时,它会将所有 10 个值复制 10 次,总共插入 100 行。

【问题讨论】:

  • 你确定你没有在外循环中使用它吗?

标签: c# datatable dataset


【解决方案1】:

dtTPositions.Clear() 放在foreach 循环之前以清除dtTPositions 中的所有项目。

修改你的代码如下:

dtTPositions.Clear();
foreach(DataRow dtTP in sltsrcTfobs.Rows) {
    DataRow destRow = dtTPositions.NewRow();
    destRow["SystemOrdinal"] = dtTP["PosID"];
    dtTPositions.Rows.Add(destRow);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2013-07-02
    • 2023-03-16
    • 1970-01-01
    • 2012-11-24
    • 2018-10-31
    • 2015-01-02
    相关资源
    最近更新 更多