简体   繁体   中英

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);

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);
}

Use NewRow() function of the new table and then use oRow.ItemArray property to get values from the source row and copy them the newly created row's ItemArray . An example would be:

Array.Copy(oRow.ItemArray, oNewTable.NewRow().ItemArray, oRow.ItemArray.Length)

However, remember that this would not preserve original values and current state from the source row (which I don't think you're using here anyway). If those things matter, go for ImportRow() solution which preserves source row's state when copying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM