Wednesday, March 7, 2012

MyDataTable.NewRow() - Looping issue

Code:

DataRow dr;foreach (object chkedin chklst.CheckedItems)

{

dr = qrequest.NewRow();

dr = queries.Tables[0].Rows.Find(chked);

qrequest.Rows.Add(dr);

}

it makes it through the loop once just fine but when it goes around for time number 2 it says the object is already in the table. I cant really say i know what im doing here, but i do (sort of) understand why its doing this. the question is, how do i get around this?

I actually got this code from MSDN (they used a for loop and added multiple rows to a table just like this)

Thanks

Justin

You should try declaring your row inside the for loop; that way the variable is initialized during each cycle. Otherwise, the row still holds the reference to the last row (which you just added to the table).

foreach (object chkedin chklst.CheckedItems) {DataRow dr; dr = qrequest.NewRow();dr = queries.Tables[0].Rows.Find(chked);qrequest.Rows.Add(dr);}

Also, is qrequest empty to begin with? If it has any of the rows that are returned from queries.Tables(0).Rows.Find() then that will cause a redundancy error. But mostly I think your issue is what I described above.

|||

I actually tried that and i got the same error, did it ever so slightly different, did the declare as one line: DataRow dr = new DataRow();

i cant realy imagine thats any different than what you did but it still gave me the same error.

|||

Hi,

I'm not quite sure what you're trying to do. But there are some problems in the code.

1. The dr = qrequest.NewRow(); line will have no use because the next line points dr to the other DataRow instance.
2. The found row already belongs to a certain table and it cannot be added to another DataTable. In this case, you will need to use ImportRow() method instead.

|||

yeah my biggest problem was #2. which is i guess a direct result of #1. either way i did find a way around it but i must have over looked the importrow which is exactly what i need.

If i dont define columns for the table im importing to does it create them automatically based on the row im importing?

Thanks

Justin

|||

No, Justin. We can only import rows according to the current schema.

HTH. If this does not answer you question, please feel free to mark it as Not Answered and post your reply. Thanks!

No comments:

Post a Comment