Datatable.Importrow data type conversion

Lance James 371 Reputation points
2022-03-18T21:22:55.897+00:00

I thought I had this working but was just lucky that the data source shared the same data types per column with the table. This is not the general case so I hit a wall.

I have a spreadsheet read into a datatable. I clone the table so I can Add columns, change Data Types of columns, and delete all excess columns. The data will be put into a SQL table.

The adding and changing of data type on the clone is fine. The failure occurs with the data copy.

                                da.SelectCommand = cmd;
                                da.Fill(dt);

                                dtClone = dt.Clone();

                                DataOperations.AddColumns(ref dtClone);

                                DataOperations.UpdateDataType(ref dtClone);

                                //Copy data from original Datatable to Clone
                                foreach (DataRow dataRow in dt.Rows)
                                {
                                    Console.WriteLine(dataRow.ToString());

                                    dtClone.ImportRow(dataRow);
                                }

After the copy I intend to do the deleting of excess columns.

Do I simply copy each row and column individually casting the data type at that time or is the obvious being overlooked by me?

Regards,
Lance

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-03-19T00:34:11.103+00:00

    ImportRow has no logic built in to fix column type conversions which means you need to write code to handle each column that differs from the two tables to have a smooth import of a row.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.