Thank you for updating your question with the code.
Looking at your code, you have this line below:
dt.Rows[dt.Rows.Count - 1][i] = cell;
It looks like you are treating all values as
string
type but your
DataTable
contains a
System.DateTime
column. You need to identify the
Column
that has non-string type and perform conversion before assigning the value.
A quick and dirty example basing on your code is to do something like this:
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
if(i = 1){
DateTime documentDate = DateTime.MinValue;
if(DateTime.TryParse(cell, out documentDate)){
dt.Rows[dt.Rows.Count - 1][i] = documentDate;
}
}
else{
dt.Rows[dt.Rows.Count - 1][i] = cell;
}
i++;
}
}
}
The thing to keep a note there is we use
DateTime.TryParse
to ensure that we are passing a valid datetime string value to the column.
You may also want to look at this article that uses
schema.ini
to import CSV to SQL database:
ASP.NET WebForms: Uploading and Importing CSV File to SQL Server[
^]