Remove row from generic datatable in C#(The given DataRow is not in the current DataRowCollection)

from: http://stackoverflow.com/questions/4472757/remove-row-from-generic-datatable-in-c-sharp

I ran into a problem trying to remove a row from a datatable in 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. 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". Which doesn't make any sense, given that newData is a direct copy of data. Does anyone else have any suggestions? The MSDN site wasn't much help.

Thanks!
---------------------------------------------------------------------
Yes, you have a copy, but you don't have that exact row. If you want to remove a row from newData, you've got to reference one of the rows it contains, not a row from another table (even though it's an exact duplicate, it's still different and can't be used to remove the same row from newData). – Michael Todd Dec 17 '10 at
---------------------------------------------------------------------
Your foreach needs to be on the copy, not the original set. You cannot remove an object contained in collection1 from collection2.

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);
  }
}
----------------------------------------------------------------------
Thanks, that's what I needed. I never saw any caveats about the datatabe.copy() method, but it makes sense that it's just a copy and doesn't reference the original rows. – Greg Dec 17 '10 at 18:16

posted @ 2012-05-26 10:33  Yaoquan.Luo  阅读(1547)  评论(0编辑  收藏  举报