I am working for CSV File import to SQL Server
I got code from Internet ..working fine But when I am adding one extra field (User_Id) with that CSV file to SQL then this is giving error ....I am not able to understand where is doing mistake ....code... DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("Name");
tblReadCSV.Columns.Add("Email");
tblReadCSV.Columns.Add("Mobile");
tblReadCSV.Columns.Add("User_id");
string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Email/UploadFile/" + path));
path = Server.MapPath("~/Email/UploadFile/" + path);
TextFieldParser csvParser = new TextFieldParser(path);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true))
{
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
string strCon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string strSql = "Insert into Contacts(Name,Email,Mobile,User_id ) values(@Name,@Email,@Mobile," + UserId +")";
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50, "Name");
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 50, "Email");
cmd.Parameters.Add("@Mobile", SqlDbType.VarChar, 50, "Mobile");
cmd.Parameters.Add("@User_id", SqlDbType.Int , UserId);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
Label1.Text = "File successfully uploaded";