Reputation: 83
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.
Upvotes: 0
Views: 6018
Reputation: 1457
One way is to delete all the data in the sql table and then insert what ever the data you have in the grid view.
Another way to get around this problem is create a column with name tempid in the grid view and assign value -1 for all the new rows being inserted and on save click get the rows only with tempid=-1 and insert them into the sql table.
Upvotes: 1
Reputation: 1204
load your data to dataset and datatable in it. and one other datatable (main data) object.
after insert rows in datagrid and save clicked, check your new data with main data.
Upvotes: 0