Search code examples
c#datatable

c# adding row that already belongs to a datatable


I have a datatable DTgraph, that datatable has a column named Campaign. that column could have one of three unique values, which are IVR, City, City2`. So the rows are like this:

I have a datatable has data like this format

........ IVR........

.........IVR........

**.........IVR........**

.........City1......

.........City1......

**.........City1......**

.........City2......

.........City2......

**.........City2......**

I want to take the last row of each unique value for that column, In other words, I want to take the rows that are bold. I did almost everything like this:

var cRows = new Dictionary<string, DataRow>(StringComparer.InvariantCultureIgnoreCase);

foreach (DataRow oRow in DTgraph.Rows)
{
    var sKey = oRow["Campaign"].ToString();

    if (!cRows.ContainsKey(sKey))
    {
        cRows.Add(sKey, oRow);
    }
    else
    {
        cRows[sKey] = oRow;
    }
}

var oNewTable = DTgraph.Clone();

foreach (var oRow in cRows.Values)
{
    oNewTable.Rows.Add(oRow);
}

As you see, I put the data in dictionary and transferred the dictionary to a datatable at the end.

My problem is that on this line:

cRows.Add(sKey, oRow);

I get an error:

The row is already belongs to another datatable

Note: I need to solve that exception, I don't need a new way of doing my goal

Note: I was wrong, the exception is on this line

oNewTable.Rows.Add(oRow);

Solution

  • To be honest I don't 100% understand your question, however to fix the exception:

    The row is already belongs to another datatable.

    Change:

    oNewTable.Rows.Add(oRow);
    

    To:

    oNewTable.ImportRow(oRow);
    

    Alternatively create a new row and clone the ItemArray.

    foreach (var oRow in cRows.Values)
    {
        var newRow = oNewTable.NewRow();
        newRow.ItemArray = oRow.ItemArray.Clone() as object[];
        oNewTable.Rows.Add(newRow);
    }