Insert all data of a datagridview to database at once
I think the best way is by using TableAdapters rather than using Commands objects, its Update method sends all changes mades (Updates,Inserts and Deletes) inside a Dataset or DataTable straight TO the database. Usually when using a DataGridView you bind to a BindingSource which lets you interact with a DataSource such as Datatables or Datasets.
If you work like this, then on your bounded DataGridView you can just do:
this.customersBindingSource.EndEdit();
this.myTableAdapter.Update(this.myDataSet.Customers);
The 'customersBindingSource' is the DataSource of the DataGridView.
The adapter's Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.
From: https://msdn.microsoft.com/en-us/library/ms171933.aspx
So any changes made inside the DatagridView will be reflected on the Database when using the Update method.
More about TableAdapters: https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx
If you move your for loop, you won't have to make multiple connections. Just a quick edit to your code block (by no means completely correct):
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
As to executing multiple SQL commands at once, please look at this link: Multiple statements in single SqlCommand
Please see if below can help you
Class Post_Sales
Public Shared Sub Post_sales()
Dim ITM_ID As Integer
Dim SLS_QTY As Integer
Dim SLS_PRC As Double
Dim SLS_AMT As Double
Dim DSPL_RCT As String
Dim TAX_CODE As Integer
'Format the current date and send it to a textbox
Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))
'Open Connection
Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")
con.Open()
'Insert Records into the database
For Each rw As DataGridViewRow In Form1.DataGridView1.Rows
ITM_ID = rw.Cells("Column1").Value
DSPL_RCT = rw.Cells("Column2").Value
SLS_QTY = rw.Cells("Column3").Value
SLS_PRC = rw.Cells("Column4").Value
SLS_AMT = rw.Cells("Column5").Value
TAX_CODE = rw.Cells("Column6").Value
Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)
cmd.ExecuteNonQuery()
Next
con.Close()
MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")
End Sub
End Class