Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1682
  • Last Modified:

Copying a DataRow from one DataTable to another DataTable

OK, I'm trying to copy a DataRow from one DataTable to another DataTable.  I throw the exception: "This row already belongs to another table."  I, of course, yell at the machine, "Please make a copy of that row for me!"

      DataTable goose = new DataTable("Goose");
      dtWK = csv.ParseCSV(sFilePathName);
      DataRow dr1 = goose.Rows[5];

      DataTable duck = new DataTable("Duck");
      DataRow dr2 = duck.NewRow();
      dr2 = dr1;
      duck.Rows.Add(dr2);

I can accomplish what I want by looping thru each DataRow.ItemArray, but there must be a copy constructor somewhere, I tried DataRow.Clone(); but that doesn't seem to apply to the whole array.

      DataRow dr2 = duck.NewRow();
      int i = 0;
      foreach (object o in dr1.ItemArray)
           dr2[i++] = o.ToString();
      duck.Rows.Add(dr2);

Thanx, Jim in Vermont
0
SparrowVideo
Asked:
SparrowVideo
  • 2
1 Solution
 
mmarinovCommented:
use this

DataTable goose = new DataTable("Goose");
     dtWK = csv.ParseCSV(sFilePathName);
     DataRow dr1 = goose.Rows[5];

     DataTable duck = new DataTable("Duck");
     duck.Rows.Add(dr1.ItemArray);

B..M
0
 
KarunSKCommented:
As you might have guessed, this error message is because any datarow always "belongs" to a datatable, and cannot exist independently. So once added to a table, the same row cannot be added again to another table.

You can actually use the following stmt for what you want to do:

duck.Rows.Add(dr1.ItemArray)

HTH,
Karun.
0
 
KarunSKCommented:
Ah, forget it... I'll never learn to refresh before posting...
0
 
thulseyCommented:
I had same problem.  Thanks for mention of .ItemArray.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now