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

  • 相关阅读:
    C语言提高代码效率的几种方法
    如何写出高效率稳定的单片机代码
    位运算之 C 与或非异或
    C语言中位运算符异或“∧”的作用
    位运算之——按位与(&)操作——(快速取模算法)
    案例分析
    2018年春季个人阅读计划
    《我们应当怎样做需求分析》读书笔记
    寒假——练车、脑力风暴和辅导初中生
    需求工程:软件建模与分析 读书笔记三
  • 原文地址:https://www.cnblogs.com/luoyaoquan/p/2519034.html
Copyright © 2011-2022 走看看