• 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

  • 相关阅读:
    [JNA系列]Java调用Delphi编写的Dll之Delphi与JAVA基本数据类型对比
    JSON和数据集互相转换单元
    Windows管理多个java版本--解决'has value '1.8',but'1.7' is required'的方法
    Spring+SpringMVC+MyBatis+Maven框架整合
    让你的程序通过XP防火墙
    内存共享【Delphi版】
    自学k8s-安装docker特定版本技巧
    自学k8s-k8s集群环境搭建
    自学k8s-安装过程为下载flannel.yml和镜像文件,而需要设置的代理
    Centos开放指定端口命令
  • 原文地址:https://www.cnblogs.com/luoyaoquan/p/2519034.html
Copyright © 2020-2023  润新知