Saturday, November 20, 2004

DataTable.ImportRow method confusion - DUH!

I wrote some code in a web service the other day to pick off the first few rows of a data in a DataTable that was returned to me from someone else's data engine. The code that I wrote looked something like this:

DataTable dsTemp = new DataTable();
for (int i = 0; i <>

When I started testing the code, I found that my table was coming back with zero data rows. I was puzzled by this, because I had read the documentation for ImportRow, which states:
Calling NewRow adds a row to the table using the existing table schema, but with default values for the row, and sets the DataRowState to Added. Calling ImportRow preserves the existing DataRowState, along with other values in the row.

Well, after doing a little searching on the web, I realized that I had read this documentation incorrectly. I thought that the “existing table schema” that it was referring to was the table that you are importing the rows from, which would give your new table the same schema. Wrong! You must already have your schema set for the table that you are importing rows into. Thus, to fix my code, I made a couple of small changes:
DataSet dsTemp = ds.Clone();
for (int i = 0; i <>

Once I made this change to the code, the data was returned from my web service just as I had expected. You live and learn.