从C#中的通用数据表中删除行

时间:2010-12-17 16:44:24

标签: c# datatable row

我在尝试从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网站没什么帮助。

谢谢!

1 个答案:

答案 0 :(得分:4)

您的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);
  }
}
相关问题