【问题标题】:Remove row from generic datatable in C#从 C# 中的通用数据表中删除行
【发布时间】:2010-12-17 16:44:24
【问题描述】:

我在尝试从 C# 中的数据表中删除一行时遇到了问题。问题是数据表是从 SQL 构建的,因此它可以有任意数量的列,并且可能有也可能没有主键。因此,我无法根据某列或主键中的值删除行。

这是我正在做的事情的基本大纲:

//Set up a new datatable that is an exact copy of the datatable from the SQL table.  
newData = data.Copy();
//...(do other things)
foreach (DataRow dr in data.Rows)
{
  //...(do other things)
  // Check if the row is already in a data copy log.  If so, we don't want it in the new datatable.
  if (_DataCopyLogMaintenance.ContainedInDataCopyLog(dr))
  {
    newData.Rows.Remove(dr);
  }
}

但是,这给了我一条错误消息,“给定的 DataRow 不在当前的 DataRowCollection 中”。这没有任何意义,因为 newData 是数据的直接副本。还有其他人有什么建议吗? MSDN 网站没有太大帮助。

谢谢!

【问题讨论】:

  • 是的,你有一个副本,但你没有那个确切的行。如果要从 newData 中删除一行,则必须引用其中包含的行,而不是另一个表中的行(即使它是完全重复的,它仍然不同,不能用于删除相同的来自 newData 的行)。

标签: c# datatable row


【解决方案1】:

您的foreach 需要在副本上,而不是原始集上。您不能从 collection2 中删除 collection1 中包含的对象。

foreach (DataRow dr in newData.Rows)

否则,您可以使用计数器在索引处删除。像这样的:

for(int i = 0; i < data.Rows.Count; i++)
{
  if (_DataCopyLogMaintenance.ContainedInDataCopyLog(data.Rows[i]))
  {
    newData.Rows.RemoveAt(i);
  }
}

【讨论】:

  • 谢谢,这正是我所需要的。我从未看到有关 datatabe.copy() 方法的任何警告,但它只是一个副本并且不引用原始行是有道理的。
猜你喜欢
  • 2011-09-17
  • 2020-12-10
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
相关资源
最近更新 更多