hi ALL
I am trying to insert data from datagridview to sql, but i only insert one line or one row,
below is the code i am using.
int row = dataGridView1.Rows.Count-2;
SqlConnection conn = new SqlConnection("Data Source=KATOTO-PC;Initial Catalog =thyfarm;User ID=sa;Password=Kyozi");
conn.Open();
string insertString = "insert into Treatmentpurchases (day) values ('" + dataGridView1.Rows[row].Cells["Day"].Value + "')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
conn.Close();
any help will be highly appreciated.
Loading

Aaron ColenPosted Aug 11, 2011, 1:16 PM
The first line sets 'row' to the number of rows in your datagrid minus 2.
int row = dataGridView1.Rows.Count-2;
Further down your insert string uses the 'row' to get the value of one row from the datagridview.
string insertString = "insert into Treatmentpurchases (day) values ('" + dataGridView1.Rows[row].Cells["Day"].Value + "')";
If you are trying to insert all rows on the datagridview you would need to loop through it.
For example:
foreach(DataGridViewRow row in dataGridView1.Rows)
{
string insertString = "insert into Treatmentpurchases (day) values ('" + row.Cells["Day"].Value + "')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
}
You will of course need to modify the above to run properly but it should give you an idea of what went wrong.