error Line : DataTable dt = GetDataTabletFromCSVFile(csv_file_path);
code:
private void btnselect_Click(object sender, EventArgs e) { try { OpenFileDialog dialog = new OpenFileDialog(); dialog.ShowDialog(); int ImportedRecord = 0, inValidItem = 0; string SourceURl = ""; if (dialog.FileName != "") { if (dialog.FileName.EndsWith(".csv")) { DataTable dtNew = new DataTable(); dtNew = GetDataTabletFromCSVFile(dialog.FileName); if (Convert.ToString(dtNew.Columns[0]).ToLower() != "MachineAutoStartStop") { textFile.Text = dialog.SafeFileName; SourceURl = dialog.FileName; if (dtNew.Rows != null && dtNew.Rows.ToString() != String.Empty) { dataGridView1.DataSource = dtNew; lbltotalrecords.Text = $"Total Records: {dataGridView1.RowCount}"; } } catch (Exception ex) { MessageBox.Show("Exception " + ex); } } private DataTable GetDataTabletFromCSVFile(string csv_file_path) { DataTable csvData = new DataTable(); try {
using (Microsoft.VisualBasic.FileIO.TextFieldParser csvReader = new Microsoft.VisualBasic.FileIO.TextFieldParser(csv_file_path)) { csvReader.SetDelimiters(new string[] { "," }); csvReader.HasFieldsEnclosedInQuotes = true; //read column string[] colFields = csvReader.ReadFields(); foreach (string column in colFields) { DataColumn datecolumn = new DataColumn(column); datecolumn.AllowDBNull = true; csvData.Columns.Add(datecolumn); } while (!csvReader.EndOfData) { string[] fieldData = csvReader.ReadFields(); for (int i = 0; i < fieldData.Length; i++) { if (fieldData[i] == "") { fieldData[i] = null; } } csvData.Rows.Add(fieldData); } }
} catch (Exception ex) { MessageBox.Show("Exce " + ex); } return csvData; }
private void BtnImport_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor;
DataTable dt = GetDataTabletFromCSVFile(csv_file_path);
if (dt == null) return;
SaveImportDataToDatabase(dt);
MessageBox.Show("Data Import success!"); textFile.Text = string.Empty; Cursor = Cursors.Default;
}