Import CSV Data Into Database Using C# Windows Form Application

Here I will show you how to import CSV data into SQL Server database using C#.Net Windows Application.

Here my goal to import .csv file data into SQL Server database using Windows Forms Application with C#.Net.
 
It's an easy way to add multiple records into the database instead of creating records one by one. It saves you lots of time. So it's a good idea to import data using csv or excel file instead of creating (Adding) record one by one.
 
I hope this sample code overview will help you to achieve your goal.
 
Let me explain, what I did here?
 
I have created a Windows Forms Application and I used C# as a language in this tutorial. In this application, I created a form called frmImportItem.

So in this, I will import item(product) data into the database for my POS (Point Of Sale) Application.
 
You can have any data like Student, Employee, and patient, etc. create your file that you want to import into the database.
 
I have a sample file (CSV file) for the import that I will import into the SQL Server database.
 
Step 1
 
Create A design to import data, take a button that will open a dialog box to select CSV file and one textbox to show the selected file name.
 
Step 2
 
Also, take one DataGridView to show all the items, selected CSV file item will bind into that DataGridView and show to the user.
 
Step 3
 
Create two Button one for Save Item and Another one is Close form.
 
Step 4
 
Here I will write code for the Select file (.csv) and read data and bind to the database. To select the file and Read CSV file data and bind to a DataGridView. Check the btnSelectFile_Click ()
  1. private void btnSelectFile_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         OpenFileDialog dialog = new OpenFileDialog();  
  4.         dialog.ShowDialog();  
  5.         int ImportedRecord = 0, inValidItem = 0;  
  6.         string SourceURl = "";  
  7.         if (dialog.FileName != "") {  
  8.             if (dialog.FileName.EndsWith(".csv")) {  
  9.                 DataTable dtNew = new DataTable();  
  10.                 dtNew = GetDataTabletFromCSVFile(dialog.FileName);  
  11.                 if (Convert.ToString(dtNew.Columns[0]).ToLower() != "lookupcode") {  
  12.                     MessageBox.Show("Invalid Items File");  
  13.                     btnSave.Enabled = false;  
  14.                     return;  
  15.                 }  
  16.                 txtFile.Text = dialog.SafeFileName;  
  17.                 SourceURl = dialog.FileName;  
  18.                 if (dtNew.Rows != null && dtNew.Rows.ToString() != String.Empty) {  
  19.                     dgItems.DataSource = dtNew;  
  20.                 }  
  21.                 foreach(DataGridViewRow row in dgItems.Rows) {  
  22.                     if (Convert.ToString(row.Cells["LookupCode"].Value) == "" || row.Cells["LookupCode"].Value == null || Convert.ToString(row.Cells["ItemName"].Value) == "" || row.Cells["ItemName"].Value == null || Convert.ToString(row.Cells["DeptId"].Value) == "" || row.Cells["DeptId"].Value == null || Convert.ToString(row.Cells["Price"].Value) == "" || row.Cells["Price"].Value == null) {  
  23.                         row.DefaultCellStyle.BackColor = Color.Red;  
  24.                         inValidItem += 1;  
  25.                     } else {  
  26.                         ImportedRecord += 1;  
  27.                     }  
  28.                 }  
  29.                 if (dgItems.Rows.Count == 0) {  
  30.                     btnSave.Enabled = false;  
  31.                     MessageBox.Show("There is no data in this file""GAUTAM POS", MessageBoxButtons.OK, MessageBoxIcon.Warning);  
  32.                 }  
  33.             } else {  
  34.                 MessageBox.Show("Selected File is Invalid, Please Select valid csv file.""GAUTAM POS", MessageBoxButtons.OK, MessageBoxIcon.Warning);  
  35.             }  
  36.         }  
  37.     } catch (Exception ex) {  
  38.         MessageBox.Show("Exception " + ex);  
  39.     }  
  40. }  
  41. public static DataTable GetDataTabletFromCSVFile(string csv_file_path) {  
  42.     DataTable csvData = new DataTable();  
  43.     try {  
  44.         if (csv_file_path.EndsWith(".csv")) {  
  45.             using(Microsoft.VisualBasic.FileIO.TextFieldParser csvReader = new Microsoft.VisualBasic.FileIO.TextFieldParser(csv_file_path)) {  
  46.                 csvReader.SetDelimiters(new string[] {  
  47.                     ","  
  48.                 });  
  49.                 csvReader.HasFieldsEnclosedInQuotes = true;  
  50.                 //read column  
  51.                 string[] colFields = csvReader.ReadFields();  
  52.                 foreach(string column in colFields) {  
  53.                     DataColumn datecolumn = new DataColumn(column);  
  54.                     datecolumn.AllowDBNull = true;  
  55.                     csvData.Columns.Add(datecolumn);  
  56.                 }  
  57.                 while (!csvReader.EndOfData) {  
  58.                     string[] fieldData = csvReader.ReadFields();  
  59.                     for (int i = 0; i < fieldData.Length; i++) {  
  60.                         if (fieldData[i] == "") {  
  61.                             fieldData[i] = null;  
  62.                         }  
  63.                     }  
  64.                     csvData.Rows.Add(fieldData);  
  65.                 }  
  66.             }  
  67.         }  
  68.     } catch (Exception ex) {  
  69.         MessageBox.Show("Exce " + ex);  
  70.     }  
  71.     return csvData;  
  72. }  
Step 5
 
On the Save button, I have written code to save data into the database.
 
For this check the button click event as btnSave_Click().
  1. private void btnSave_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         DataTable dtItem = (DataTable)(dgItems.DataSource);  
  4.         string Lookup, description, dept, UnitPrice;  
  5.         string InsertItemQry = "";  
  6.         int count = 0;  
  7.         foreach(DataRow dr in dtItem.Rows) {  
  8.             Lookup = Convert.ToString(dr["LookupCode"]);  
  9.             description = Convert.ToString(dr["ItemName"]);  
  10.             dept = Convert.ToString(dr["DeptId"]);  
  11.             UnitPrice = Convert.ToString(dr["Price"]);  
  12.             if (Lookup != "" && description != "" && dept != "" && UnitPrice != "") {  
  13.                 InsertItemQry += "Insert into tbItem(LookupCode,ItemName,DeptId,CateId,Cost,Price, Quantity, UOM, Weight, TaxID, IsDiscountItem,EntryDate)Values('" + Lookup + "','" + description + "','" + dept + "','" + dr["CateId"] + "','" + dr["Cost"] + "','" + UnitPrice + "'," + dr["Quantity"] + ",'" + dr["UOM"] + "','" + dr["Weight"] + "','" + dr["TaxID"] + "','" + dr["IsDiscountItem"] + "',GETDATE()); ";  
  14.                 count++;  
  15.             }  
  16.         }  
  17.         if (InsertItemQry.Length > 0) {  
  18.             bool isSuccess = DBAccess.ExecuteQuery(InsertItemQry);  
  19.             if (isSuccess) {  
  20.                 MessageBox.Show("Item Imported Successfully, Total Imported Records : " + count + """GAUTAM POS", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  21.                 dgItems.DataSource = null;  
  22.             }  
  23.         }  
  24.     } catch (Exception ex) {  
  25.         MessageBox.Show("Exception " + ex);  
  26.     }  
  27. }  
DBAccess Class Code
------------------------------
  1. class DBAccess {  
  2.     private static SqlConnection objConnection;  
  3.     private static SqlDataAdapter objDataAdapter;  
  4.     public static string ConnectionString = @ "Data Source=GAUTAM\SQLEXPRESS; Initial Catalog=GautamPOS; User Id=sa; Password=123456";  
  5.     private static void OpenConnection() {  
  6.         try {  
  7.             if (objConnection == null) {  
  8.                 objConnection = new SqlConnection(ConnectionString);  
  9.                 objConnection.Open();  
  10.             } else {  
  11.                 if (objConnection.State != ConnectionState.Open) {  
  12.                     objConnection = new SqlConnection(ConnectionString);  
  13.                     objConnection.Open();  
  14.                 }  
  15.             }  
  16.         } catch (Exception ex) {}  
  17.     }  
  18.     private static void CloseConnection() {  
  19.         try {  
  20.             if (!(objConnection == null)) {  
  21.                 if (objConnection.State == System.Data.ConnectionState.Open) {  
  22.                     objConnection.Close();  
  23.                     objConnection.Dispose();  
  24.                 }  
  25.             }  
  26.         } catch {}  
  27.     }  
  28.     public static bool ExecuteQuery(string query) {  
  29.         try {  
  30.             using(SqlConnection connection = new SqlConnection(ConnectionString)) {  
  31.                 using(SqlCommand cmd = new SqlCommand(query, connection)) {  
  32.                     connection.Open();  
  33.                     cmd.ExecuteNonQuery();  
  34.                     connection.Close();  
  35.                     return true;  
  36.                 }  
  37.             }  
  38.         } catch (Exception ex) {  
  39.             return false;  
  40.         }  
  41.     }  
  42. }  
Check the video for your reference.