zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    剑指offer面试题17:合并两个排序的链表
    剑指offer面试题16:反转链表
    剑指offer面试题15:链表中倒数第K个节点
    Jinja2.template渲染两种常见用法
    hadoop集群运维碰到的问题汇总
    hbase配置参数总结
    hbase内核学习总结
    zookeeper学习笔记
    mongodb 3.2性能测试
    kafka内部结构笔记
  • 原文地址:https://www.cnblogs.com/luoyaoquan/p/2519034.html
Copyright © 2011-2022 走看看