DataTable Data Conversion Issue

May 21 2020 4:12 PM
I created a dataTable

DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
dt.Columns.Add("Col1", typeof(string));
dt.Columns.Add("Col2", typeof(string));
dt.Columns.Add("Col3", typeof(int));
For Loop
dr = dt.NewRow();
dr["Col1"] = res.Element(ns + "FirstName").Value;
dr["Col2"] = res.Element(ns + "LastName").Value;
dr["Col3"] = Convert.ToInt32(res.Element(ns + "BadgeNo").Value);
//loop
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName = "dbo.EMP_TABLE";
bulkCopy.WriteToServer(dt);
}

Upon bulk insert, I get the below error
The given value of type String from the data source cannot be converted to type int of the specified target column.

The problem is with the badgeNo, i tried converting all the ways also send hardcode data, i still get the same error.
in the SQL table, badge number is defined as int.
If i send only the FirstName and LastName, it works. When i add the BadgeNo, I get this issue.

Answers (4)