简体   繁体   English

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

[英]Remove row from generic datatable in C#

I ran into a problem trying to remove a row from a datatable in C#. 我试图从C#中的数据表中删除一行时遇到了问题。 The problem is that the datatable is built from SQL, so it can have any number of columns and may or may not have a primary key. 问题是数据表是从SQL构建的,因此它可以包含任意数量的列,可能有也可能没有主键。 So, I can't remove a row based on a value in a certain column or on a primary key. 因此,我无法根据特定列或主键中的值删除行。

Here's the basic outline of what I'm doing: 这是我正在做的基本概述:

//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);
  }
}

But, that gives me an error message, "The given DataRow is not in the current DataRowCollection". 但是,这给了我一条错误消息,“给定的DataRow不在当前的DataRowCollection中”。 Which doesn't make any sense, given that newData is a direct copy of data. 鉴于newData是数据的直接副本,这没有任何意义。 Does anyone else have any suggestions? 有没有人有任何建议? The MSDN site wasn't much help. MSDN网站没有多大帮助。

Thanks! 谢谢!

Your foreach needs to be on the copy, not the original set. 您的foreach需要在副本上,而不是原始集。 You cannot remove an object contained in collection1 from collection2. 您无法从collection2中删除collection1中包含的对象。

foreach (DataRow dr in newData.Rows)

Otherwise you could use a counter to remove at an index. 否则,您可以使用计数器在索引处删除。 Something like this: 像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM