I have 2 columns which are Name and Price. Assume that there are already some data in the database table which will be shown in the datagridview. Now, when users entered the new rows of data(no matter how many rows), and they click on the Save button, all the new rows of data will be save into the database.
The question is, how do I catch only the new rows of data? OR how do I check if the name exist, check if the price same, then do not insert, if different price, then update the price.
Here is my code:
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i<dataGridView1.Rows.Count; i++ )
{
String insertData = "INSERT INTO CostList(SupplierName, CostPrice, PartsID) VALUES (@SupplierName, @CostPrice, @PartsID)" ;
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("@SupplierName", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@CostPrice", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@PartsID", textBox1.Text);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
EDIT : the above code will add every data in the datagridview into database and keep on duplicating.
Thanks for your attention.