I have a DataTable which has 10 columns, and after I add some rows in it, I want to add it to the database using
My problem is that in the DataTable I have strings and some fields in the database are decimal and date respectively. Is there a way to convert them to the desired data types?
When programmatically adding columns to your DataTable, you can specify type:-
DataTable dt = new DataTable(); dt.Columns.Add("FieldName", typeof(System.Decimal));
These will be honored when you perform the bulk copy.
In response to user comment.
When populating the DataRow with information, an explicit conversion is only required if the source data doesn't match the target field.
If the types are the same, you can just assign it.
// With a decimal field, decimal target Decimal myNum = 123; // Works fine - assuming the Price datacolumn has been set up as a System.Decimal row["Price"] = myNum;
Sounds like you may be creating the columns in the DataTable in code (as opposed to Filling via a DataAdapter which would set the column data types appropriately).
If that's the case, then can you not just create the DataColumns with the correct data types to start with, instead of all strings...and then ensure when you add rows to it, you convert the data into the appropriate type?
i.e. get to the point where your DataTable has the correct types and data in correctly, so SqlBulkCopy can then blast it into the DB with data already in the correct form.