Wilrod
Wilrod

Reputation: 47

Why duplicate records when copying a row from a datatable to another

I'm trying to copy all the rows on a column from one datatable to another. When doing so the records duplicate.

This is what I'm doing:

foreach(DataRow dtTP in sltsrcTfobs.Rows) {
    DataRow destRow = dtTPositions.NewRow();
    destRow["SystemOrdinal"] = dtTP["PosID"];
    dtTPositions.Rows.Add(destRow);
}

This column has only int values. For example at the moment it has 10 rows, the values are 1,2,3,4,5,6,7,8,9,10. When I copy the rows to the new datatable 'dtTPositions' it copies all 10 values 10 times, inserting a total of 100 rows.

Upvotes: 0

Views: 162

Answers (1)

Bijay Koirala
Bijay Koirala

Reputation: 242

Put dtTPositions.Clear() before foreach loop to clear all the items from dtTPositions.

Modify your code as below:

dtTPositions.Clear();
foreach(DataRow dtTP in sltsrcTfobs.Rows) {
    DataRow destRow = dtTPositions.NewRow();
    destRow["SystemOrdinal"] = dtTP["PosID"];
    dtTPositions.Rows.Add(destRow);
}

Upvotes: 1

Related Questions